blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
8e0281a00c02313a9667e7243c2c6457535ea0ad | binderclip/code-snippets-python | /packages/bisect_sp/binary_search_list.py | 1,709 | 4.125 | 4 | import bisect
def reverse_bisect_right(a, x, lo=0, hi=None):
"""Return the index where to insert item x in list a, assuming a is sorted in descending order.
The return value i is such that all e in a[:i] have e >= x, and all e in
a[i:] have e < x. So if x already appears in the list, a.insert(x) will
insert just after the rightmost x already there.
Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched.
Essentially, the function returns number of elements in a which are >= than x.
>>> a = [8, 6, 5, 4, 2]
>>> reverse_bisect_right(a, 5)
3
>>> a[:reverse_bisect_right(a, 5)]
[8, 6, 5]
"""
if lo < 0:
raise ValueError('lo must be non-negative')
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
if x > a[mid]: hi = mid
else: lo = mid+1
return lo
def main():
# asc
print('=== asc ===')
l = [1, 3, 5]
print(bisect.bisect_left(l, 2))
print(bisect.bisect_left(l, 3))
print(bisect.bisect_left(l, 4))
print(bisect.bisect_left(l, 7))
print(bisect.bisect_right(l, 2))
print(bisect.bisect_right(l, 3))
print(bisect.bisect_right(l, 4))
print(bisect.bisect_right(l, 7))
# desc
print('=== desc ===')
l = [5, 3, 1]
print(reverse_bisect_right(l, 2))
print(reverse_bisect_right(l, 3))
print(reverse_bisect_right(l, 4))
print(reverse_bisect_right(l, 7))
if __name__ == '__main__':
main()
# https://stackoverflow.com/questions/2591159/find-next-lower-item-in-a-sorted-list
# https://stackoverflow.com/questions/2247394/python-bisect-it-is-possible-to-work-with-descending-sorted-lists
|
b14a2758d85cc179536230387134f34b26df5df9 | gr3grisch/awesomePython | /code/command_lines.py | 279 | 3.796875 | 4 | import sys
if __name__ == '__main__':
arguments = sys.argv()
if arguments == 3:
a, b, c = tuple(arguments)
for i in arguments: (
print('%s %s %s' % (a, b, c)))
else:
print('iLLegal number of arguments: must be 3')
|
d93a5e4c86c1b4120a85db352cff3e90b9a4296c | timeisthelimit/IRCServer | /server.py | 6,379 | 3.5625 | 4 | #!/usr/bin/env python3
# Socket code inspired by and taken from RealPython tutorial
# on sockets (https://realpython.com/python-sockets/)
from messageparser import MessageParser
from client import Client
import serverfunctions as sfn
import socket
import selectors
import time
command_handlers = {'JOIN':sfn.handle_JOIN, 'PRIVMSG':sfn.handle_PRIVMSG}
mp = MessageParser()
class Server:
# dict of channel names to Channel class object
_channels = {}
# dict of nicks to (<client socket>, <Client object>) tuples
_clients = {}
def getClients(self):
return self._clients
def addClient(self, nick, client_socket, client_object):
self._clients[nick] = (client_socket, client_object)
def deleteClient(self, nick):
self._clients.pop(nick, None)
def getChannels(self):
return self._channels
def addChannel(self, channel_name, channel_object):
self._channels[channel_name] = channel_object
def deleteChannel(self, channel_name):
self._channels.pop(channel_name, None)
sock_selector = selectors.DefaultSelector()
mp = MessageParser()
server = Server()
HOST = '127.0.0.1'
PORT = 6667
#accept client connection
def accept_connection(server_sock):
conn, addr = server_sock.accept()
conn.setblocking(False)
# object for storing client details
client = Client()
nick_set = user_set = False
# registration attempts
attemps = 0
registration_start_time = time.time()
while not nick_set or not user_set:
# After 5 messages it timesout
# The socket should take care of an actaul timeout (ms)
if attemps>3:
sfn.no_reg(conn, HOST)
conn.close()
# close socket
return
if registration_start_time+0.1 < time.time():
return
messages=None
# try to receive from the client socket
# simply registring the newly accepted socket with our socket
# and the handling registration in service connection is another option
# which might have been slightly better
try:
messages = conn.recv(512).decode().split('\n')
except IOError as e:
if e.errno == socket.EWOULDBLOCK:
pass
else:
sfn.serv_log(str(e))
except Exception as e:
sfn.serv_log(str(e))
return
if messages is not None:
for m in messages:
if m != '':
sfn.irc_log("IN", m)
prefix, command, params = mp.parseMessage(m)
if command == "NICK":
if len(params) <1 :
sfn.no_nick(conn, HOST)
else:
client.reg_nick(params[0])
if client.nick in server.getClients().keys():
attemps +=1
sfn.nick_collision(conn, client, HOST)
nick_set = False
else:
nick_set = True
elif command == "USER":
client.reg_user(*params)
user_set = True
else:
attemps+=1
if not nick_set:
sfn.no_nick(conn, HOST)
if nick_set and user_set:
sfn.confirm_reg(conn, client, HOST)
sfn.serv_log("User {} has logged in".format(client.username))
server.addClient(client.nick, conn, client)
mask = selectors.EVENT_READ | selectors.EVENT_WRITE
sock_selector.register(conn, mask, client)
sfn.serv_log('{} connected!'.format(addr))
# service client connection
def service_connection(key, mask):
conn = key.fileobj
client = key.data
if mask & selectors.EVENT_WRITE:
# ping client if they haven't been pinged in the last 10 seconds
if client.timestamp+10 < time.time():
client.update_timestamp()
msg = "PING {}\r\n".format(client.nick)
sfn.irc_log("OUT",msg.strip())
conn.sendall(msg.encode())
if mask & selectors.EVENT_READ:
messages = conn.recv(512).decode().split('\n')
# split messages and queue them in inboud buffer
for m in messages:
if m != '':
sfn.irc_log("IN", m)
client.inb.append(m)
# pop one message off inbound buffer and handle it
# using a try block because it is expected that if we are reading
# then there should be a message ready to be popped,
# thus empty list means an problem occured somewhere else
try:
prefix, command, params = mp.parseMessage(client.inb.pop(0))
except Exception as e:
sfn.remove_client(key, sock_selector, server)
sfn.serv_log(str(e))
sfn.serv_log("Safely removed client of nick '{}' from server".format(client.nick))
if command == "QUIT":
sfn.remove_client(key, sock_selector, server)
return
# attempt to execute command extrapolated from the message
# inform server if the command is not in our command_handlers dictionary
try:
command_handlers[command](params, server, client, HOST)
except KeyError as e:
sfn.serv_log("Unhandled IRC Command:" + str(e))
except Exception as e:
sfn.remove_client(key, sock_selector, server)
sfn.serv_log(str(e))
sfn.serv_log("Safely removed client of nick '{}' from server".format(client.nick))
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('127.0.0.1', 6667))
s.listen()
s.setblocking(False)
sock_selector.register(s, selectors.EVENT_READ, data=None)
while True:
# Get a list of all sockets which are ready to be written to, read from, or both
events = sock_selector.select(timeout=None)
for key, mask in events:
if key.data is None:
accept_connection(key.fileobj)
else:
service_connection(key, mask)
|
fb55ff6cb66e4d4e90f2eef2066c39d256bf8825 | GiovannaPazello/Projetos-em-Python | /Lista 3/Exercicio 6.py | 339 | 3.875 | 4 | '''Faça um programa que leia um número digitado pelo usuário. Depois, informe todos os
números primos gerados até o número digitado pelo usuário.'''
n = int(input("Verificar números primos até:"))
cont=0
nPrimos = []
for i in range(2,n):
if (n % i == 0):
cont += 1
if(cont==0):
nPrimos.append(n)
print(nPrimos) |
53a254993bba196b165c27623c7ff99882fbcba3 | manhalrahman/Turtle-Module-Shapes | /turtle_polygons.py | 1,058 | 4.40625 | 4 | from turtle import Turtle, Screen
from random import randint
timmy = Turtle()
timmy.color("black") #Need not be there
my_screen = Screen()
# This code moves the turtle upwards a little bit as the shapes will grow downwards and may escape the screen
timmy.penup() #So the we don't see the turtle moving up to the top of the screen
timmy.goto(0, 290) #The canvas dimensions are 300 height, 400 width. Just lifts the turtle towards the top
timmy.pendown() #So that we can draw again
#Draws all the shape
def draw_shapes(start=3, end=10, sidelength=100):
my_screen.colormode(255)
#All the polygons will have number of sides in the range [start, end]
for sides in range(start, end+1):
timmy.color(randint(0, 255), randint(0, 255), randint(0, 255)) #A random color for each movement
for i in range(sides):
angle = 360 / sides
timmy.forward(sidelength)
timmy.right(angle)
draw_shapes(3, 30, 50)
my_screen.exitonclick() #Click on the screen to close it. Will work after all the shapes are drawn.
|
6261e3572a1be749b24a3f76a429b6dfb5634c9e | casheljp/pythonlabs | /examples/4/working_with_lists.py | 502 | 3.828125 | 4 | #!/usr/bin/env python3
lis = [10, 20, 30, 40, 20, 50]
fmt = "%32s %s"
print(fmt % ("Original:", lis))
print(fmt % ("Pop Last Element:", lis.pop()))
print(fmt % ("Pop Element at pos# 2:", lis.pop(2)))
print(fmt % ("Resulting List:", lis))
lis.append(100)
print(fmt % ("Appended 100:", lis))
lis.remove(20)
print(fmt % ("Removed First 20:", lis))
lis.insert(1, 1000)
print(fmt % ("Inserted 1000 at pos# 1:", lis))
lis.sort()
print(fmt % ("Sorted:", lis))
lis.reverse()
print(fmt % ("Reversed:", lis))
|
279a50786dff9fd06ac053b2a3d2bf4d66e21d5d | apabon03/datacademy-python-cardio | /area-triangulo.py | 1,289 | 3.9375 | 4 | def tipo_triangulo(lado_a, lado_b, lado_c):
if lado_a== lado_b and lado_b == lado_c:
print("El triángulo es equilatero")
elif lado_a != lado_b and lado_b == lado_c:
print("El triángulo es Isósceles")
else:
print("El triángulo es Escaleno")
def area(base, altura):
return (base * altura)/2
def run():
menu = True
while menu == True:
opcion = input('''
Menú:
1. Área del triángulo.
2. Tipo de triángulo: Escaleno, Isósceles, Equilátero
3. Salir del programa.
Bienvenido, elige qué deseas calcular: ''')
if opcion == '1':
base = int(input("Ingresa la base: "))
altura = int(input("Ingresa la altura: "))
print(f'El área del triángulo es: {area(base, altura)}')
elif opcion == '2':
lado_a = int(input("Ingresa el primer lado: "))
lado_b = int(input("Ingresa el segundo lado: "))
lado_c = int(input("Ingresa el tercer lado: "))
tipo_triangulo(lado_a, lado_b, lado_c)
elif opcion == '3':
menu = False
else:
print("Ingrese una opción válida: ")
if __name__ == "__main__":
run() |
55f21f7565072d2a2ff6fd2adc28052c8a41c46b | ruzguz/python-stuff | /8-lists/hangman.py | 2,392 | 3.921875 | 4 | # -*- coding: utf-8 -*-
import random
IMAGES = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
/|\ |
|
|
=========''', '''
+---+
| |
O |
/|\ |
| |
|
=========''', '''
+---+
| |
O |
/|\ |
| |
/ |
=========''', '''
+---+
| |
O |
/|\ |
| |
/ \ |
=========''', '''
''']
WORDS = [
'hello',
'goodbye',
'code',
'computer',
'theme',
'clear',
'word',
'hangman',
'pencil',
'ruler',
'website'
]
def random_word():
i = random.randint(0, len(WORDS) - 1)
return WORDS[i]
def display_board(hidden, tries):
print(IMAGES[tries])
print('')
print(hidden)
print('--- * --- * --- * --- * --- * --- * ---')
def run():
word = random_word()
hidden_word = ['-'] * len(word)
tries = 0
while True:
display_board(hidden_word, tries)
current_letter = str(input('Try a letter: '))
letter_indexes = []
for i in range(len(word)):
if word[i] == current_letter:
letter_indexes.append(i)
if len(letter_indexes) == 0:
tries += 1
else:
for i in letter_indexes:
hidden_word[i] = current_letter
letter_indexes = []
# check if the player wins
if hidden_word.count('-') == 0:
print('--- * --- * --- * --- * --- * --- * ---')
print('YOU WIN!!!')
print('--- * --- * --- * --- * --- * --- * ---')
break
# check if player loses
if tries == len(IMAGES) - 1:
print('--- * --- * --- * --- * --- * --- * ---')
print('better luck next time :(, the word was {}'.format(word))
print('--- * --- * --- * --- * --- * --- * ---')
break
if __name__ == '__main__':
print('W E L C O M E T O H A N G M A N')
run()
input('thanks for playing, press enter to exit of the game.') |
692063a16414f4defdc57fdb0e3a08a4c7ae408b | trewto/guitarchoardchanger | /guitar.py | 763 | 3.5625 | 4 |
l = ["A","A#","B","C","C#","D","D#","E","F","F#","G","G#"]
l1 = ["Am","A#m","Bm","Cm","C#m","Dm","D#m","Em","Fm","F#m","Gm","G#m"]
print("How many Choard?")
n = input()
n = int(n)
d = []
i = 0
while i<n:
f = input()
d = d + [f]
i = i +1
print("====================")
def scale_up(choard,level):
c = num(choard)
if c>= 100:
c = c- 100
if c+level<12:
q= c+ level
else:
q= (c+level)-12
return l1[q]
else:
if c+level<12:
q= c+ level
else:
q= (c+level)-12
return l[q]
def num(choard):
p=-1
for t in l:
p= p+1
if t == choard:
return p
break
p = 99
for t in l1:
p= p+1
if t == choard:
return p
break
i=0
while(i<12):
n = []
for z in d:
n = n + [scale_up(z,i)]
i= i +1
print(str(n))
input()
|
af35ac15ec5b9ec2cd702b72827693d7082e7409 | unmeg/misc-ML | /pytorch-blitz-notes.py | 5,382 | 3.984375 | 4 | """
Notes to self for http://pytorch.org/tutorials/beginner/blitz/neural_networks_tutorial.html
Looking at the network diagram, we take an input that is 32x32x3 and we convolve, downsample
and then spit it out into some fully connected layers.
Let's unpack.
To go from input >> C1, we see a convolution. The input is 32x32 and we need our convolution
to give us a 6-filter output with dimensions 28x28. To find the kernel size that gives us
such an output, we simply use the formula I stole from CS231n:
output = (input - kernel / stride) + 1. We can rearrange to solve for kernel..
We get kernel = (output - input / stride) + 1
In this instance we can see that: k = (4/1) + 1 = 5. So we need a 5x5 kernel for our first
convolution.
Repeating this process for the second convolution (which we see mapping S2 >> C3), gives us
the same result.
We define these in init because that's where we lay out the learnable layers. We'll define
the functions that relate those layers in the forward method, which must be implemented.
The rest of our init is comprised of linear layers. Params are input size, output size.
"""
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 6, 5) # gives us c1 where we go from 32x32 >> 28x28
self.conv2 = nn.Conv2d(6, 16, 5) # gives us c3 14x14 >> 10x10
self.fc1 = nn.Linear(16 * 5 * 5, 120) # this takes max pool output, which will be flattened, after C3
self.fc2 = nn.Linear(120, 84) # c5
self.fc3 = nn.Linear(84, 10) # f6
def forward(self, x):
x = F.max_pool2d(F.relu(self.conv1(x)), (2,2)) # input to s2
x = F.max_pool2d(F.relu(self.conv2(x)), 2) # equivalent to (2,2). s2 to s4
x = x.view(-1, self.num_flat_features(x))
# This ^ reshapes the tensor. We don't know how many rows we want but we know
# how many columns we have. The result is a [<whatever python feels is right>, num_flat_features(x)] tensor.
# We're flattening a tensor with a depth of 16 so we can feed it to the FC layer.
x = F.relu(self.fc1(x)) # pool > 120
x = F.relu(self.fc2(x)) # 120 > 84
x = self.fc3(x) #84 > 10
return x
def num_flat_features(self, x):
size = x.size()[1:] # ignore the batch dimensions, grab everything else
num_features = 1
for s in size:
num_features *= s
return num_features
net = Net()
print(net)
"""
Net(
(conv1): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1))
(conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
(fc1): Linear(in_features=400, out_features=120, bias=True)
(fc2): Linear(in_features=120, out_features=84, bias=True)
(fc3): Linear(in_features=84, out_features=10, bias=True)
)
"""
params = list(net.parameters())
print(len(params))
print(params[0].size())
"""
10
torch.Size([6, 1, 5, 5])
"""
# Note: This is for 32x32 images, so everything else needs to be resized (i.e. MNIST)
input = Variable(torch.randn(1, 1, 32, 32))
out = net(input)
print(out)
"""
Variable containing:
0.0208 -0.0077 -0.0682 -0.0419 -0.0150 -0.1079 -0.0107 0.0379 0.0167 -0.0348
[torch.FloatTensor of size 1x10]
"""
# The Variable allows us to auto-grad for backprop! Gotta zero the network gradients
# before we use backward. PyTorch gradients are cumulative to facilitate some architectures
# (i.e. GANs). For non-cumulative gradients, we reset the gradient ourselves.
net.zero_grad()
out.backward(torch.randn(1,10)) # TODO why rando? initialisation?
# Loss
output = net(input)
target = Variable(torch.arange(1, 11))
criterion = nn.MSELoss()
loss = criterion(output, target)
print(loss)
"""
Variable containing:
38.6910
[torch.FloatTensor of size 1]
"""
"""
From the tutorial:
If we were to follow loss backward using .grad_fn, computational graph looks like this:
input -> conv2d -> relu -> maxpool2d -> conv2d -> relu -> maxpool2d
-> view -> linear -> relu -> linear -> relu -> linear
-> MSELoss
-> loss
When we call loss.backward(), the graph is differentiated wrt the loss, and all Variable's
.grad will be accumulated with the gradient.
Backward steps:
"""
print(loss.grad_fn) # MSELoss
print(loss.grad_fn.next_functions[0][0]) # Linear
print(loss.grad_fn.next_functions[0][0].next_functions[0][0]) # ReLU
"""
<MseLossBackward object at 0x7fc8bc7c6160>
<AddmmBackward object at 0x7fc8bc7c6240>
<ExpandBackward object at 0x7fc8bc7c6240>
"""
# Remember to zero the grad
net.zero_grad()
print('Conv1.bias.grad before backprop')
print(net.conv1.bias.grad)
loss.backward()
print('After')
print(net.conv1.bias.grad)
"""
Conv1.bias.grad before backprop
Variable containing:
0
0
0
0
0
0
[torch.FloatTensor of size 6]
After
Variable containing:
1.00000e-02 *
2.1366
-1.0169
4.8340
-2.1016
0.6366
-2.8716
[torch.FloatTensor of size 6]
"""
# Weights
# Update them using SGD
# learning_rate = 0.01 # hyper param
# for f in net.parameters():
# f.data.sub_(f.grad.data * learning_rate)
import torch.optim as optim
# create this bad boy
optimizer = optim.SGD(net.parameters(), lr=0.01)
# TRAINING loop
optimizer.zero_grad()
output = net(input)
loss = criterion(output, target)
loss.backward
optimizer.step() # does the update |
71325f81b9817867d79f1fc4ae27fd3a918223d2 | prafulpatel16/python-practice | /python-basics/3_assign_vars.py | 117 | 3.828125 | 4 | a = 5
print("The value of a is:" + str(a))
a = [1,2,3,4]
for i in range(4):
print(a[i], end = "")
|
997e4d9104098fa182eaea1cdd1eac3935052eb1 | mcndjxlefnd/CIS5 | /adder/main.py | 2,350 | 3.609375 | 4 | import tkinter as tk
#import variables
high = 1
low = 0
source = high
def transistor (collector,base):
if base:
return collector
else:
return low
def gate_and (A,B):
return transistor(transistor(source,A),B)
def gate_or (A,B):
if transistor(source,A):
return high
elif transistor(source,B):
return high
else:
return low
def gate_nand (A,B):
if transistor(transistor(source,A),B):
return low
else:
return high
def gate_xor (A,B):
return gate_and(gate_nand(A,B),gate_or(A,B))
def full_adder (A,B,c_in):
global sum_out, c_out
sum_out = gate_xor(gate_xor(A,B),c_in)
c_out = gate_or(gate_and(gate_xor(A,B),c_in),gate_and(A,B))
def fadd():
global num1
global num2
num1=int(addend_1.get())
num2=int(addend_2.get())
binnum1 = bin(num1)
binnum2 = bin(num2)
def bitlength(binnum):
binary = binnum[2:]
return len(binary)
if bitlength(binnum1) >= bitlength(binnum2):
wordlength = bitlength(binnum1)
else:
wordlength = bitlength(binnum2)
binlist1 = [int(i) for i in list('{0:0b}'.format(num1))]
binlist2 = [int(i) for i in list('{0:0b}'.format(num2))]
def samelength(binlist):
while len(binlist) < wordlength:
binlist.insert(0,0)
samelength(binlist1)
samelength(binlist2)
c_in = 0
result = []
while wordlength > 0:
n = 0
n += 1
bit1 = binlist1.pop()
bit2 = binlist2.pop()
full_adder(bit1,bit2,c_in)
result.insert(0,sum_out)
c_in = c_out
wordlength = wordlength-1
result.insert(0,c_out)
count = 0
summ = 0
while len(result) > 0:
if result.pop():
summ += 2**count
count = count+1
lbl_result["text"] = f"{summ}"
##########################################################################
window=tk.Tk()
window.title("Natural Number Addition")
frm_entry = tk.Frame(master=window)
addend_1 = tk.Entry(master=frm_entry, width=20)
lbl_plus = tk.Label(master=frm_entry, text="+")
addend_2 = tk.Entry(master=frm_entry, width=20)
addend_1.grid(row=0, column=0, sticky="e")
lbl_plus.grid(row=0, column=1, sticky="w")
addend_2.grid(row=0, column=2)
btn_add=tk.Button(master=window, text="=", command=fadd)
lbl_result = tk.Label(master=window)
frm_entry.grid(row=0, column=0, padx=10)
btn_add.grid(row=0, column=1, pady=10)
lbl_result.grid(row=0, column=2, padx=10)
window.mainloop()
########################################################################
|
775bcbaa02ca25d70ef353757f3dca88b59ab9a8 | srikrishna98/Machine-Learning-Assignments | /perceptron.py | 1,027 | 3.59375 | 4 | def predict(row, weights):
activation = weights[0]
for i in range(len(row) - 1):
activation += weights[i + 1] * row[i]
return 1.0 if activation >= 0.0 else 0.0
# Estimate Perceptron weights using the formula used in class
def train_weights(train, l_rate, n_epoch):
weights = [0.0 for i in range(len(train[0]))]
for epoch in range(n_epoch):
sum_error = 0.0
for row in train:
prediction = predict(row, weights)
error = row[-1] - prediction
sum_error += error ** 2
weights[0] = weights[0] + l_rate * error
for i in range(len(row) - 1):
weights[i + 1] = weights[i + 1] + l_rate * error * row[i]
print('>epoch=%d, lrate=%.3f, error=%.3f' % (epoch, l_rate, sum_error))
print(weights)
return weights
# Calculate weights
dataset = [[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 1]]
l_rate = 0.25
n_epoch = 5
weights = train_weights(dataset, l_rate, n_epoch)
print('Final Weights:')
print(weights)
|
ba469fcaea1709778700ee45ffe097dc16e4dde9 | kiran9k/Assignment2 | /k_way_merge.py | 3,654 | 3.640625 | 4 | #k-way merge sort
#!/usr/bin/python
import math
import time
import random
start=time.time()
def heapify(b,d):
N=len(b)
if(N>1):
h=int(math.ceil(math.log(N,2)))
l=int(math.floor((len(b)/2.0)))
if(h==0):
h=1
for k in range(0,h):
for i in range(l,k,-1):
i=i-1
j=(2*i +1)
if j<N-1:
if(b[j]<b[j+1]):
if(b[i]>b[j]):
b=swap(b,i,j)
d=swap(d,i,j)
else:
if(b[j+1]<b[i]):
b=swap(b,i,j+1)
d=swap(d,i,j+1)
else:
if(b[j]<b[i]):
b=swap(b,i,j)
d=swap(d,i,j)
return b,d
def swap(b,i,j):
t=b[i]
b[i]=b[j]
b[j]=t
return b
def append_initial_elements(a,c,d,x):## x=len(a)
b=[]
for i in range(0,x):
if(a[i]<>[]):
b.append(a[i][0])
c.append(0)
d.append(i)
while(len(c)<x):
c.append(0)
return b
def add_elements(a,b,c,d):
z=d[0]
y=c[z]
x=len(a[z])
if(y+1<x):
l=[]
y=y+1
c[z]=y
r= a[z][y]
r=int(r)
b[0]=r
else:
l=[]
q=[]
M=len(b)-1
for i in range(0,M):
l.append(b[i+1])
q.append(d[i+1])
b=l
d=q
return b,d
def k_way(a):
b=[]
c=[]
d=[]
e=[]
if(a==[]):
pass
elif(isinstance(a[0],int)==True):
e.extend(a)
else:
N=0
b=append_initial_elements(a,c,d,len(a))
for i in range (0,len(a)):
N=len(a[i])+N
for i in range (0,N):
b,d=heapify(b,d)
e.append(b[0])
z=d[0]
b,d=add_elements(a,b,c,d)
return e
if(__name__=='__main__'):
e=[]
for j in range(0,100):
q=[]
a=[]
for i in range (random.randint(0,5)):
a.append([])
a[i].extend(random.sample(range(-20,60),random.randint(0,20)))
a[i].sort()
#a=[1,2,3,4,5,6,7]
print "input =",a
if(a<>[] and isinstance(a[0],int)==False):
for i in range(len(a)):
q.extend(a[i])
else:
q.extend(a)
q.sort()
e=k_way(a)
#print "\n\nthe final sorted array:\n"
print e
#print b
if(q==e):
print "ok"
else:
print "failed"
print j
print a
print e
print q
break
print "###"
print "time for exec ",time.time()-start
""" a- large array which is split into parts.array b holds one element from each of these parts
array c- used to remember the position of the element in the a[i][j]
here c contains the value of j for each element in b
the array -d is used to keep track of the reshuffling of elements in b
whenever any of elements in b is reshufled, elements of d are also shuffled"""
"""elements to be given in the form of 2-D elements table"""
|
92a2bf3ddc5462e043a56e5ee2da66dc027507a8 | flacogabrielc/Selenium_Python | /Clase 3/EjC2_profe.py | 520 | 3.9375 | 4 | nombre= input("Ingrese el nombre: ")
apellido= input("Ingrese el apellido: ")
mate= int(input("Ingrese la nota de matematicas: "))
lite= int(input("Ingrese la nota de literatura: "))
fisi= int(input("Ingrese la nota de fisica: "))
prom= (mate + lite + fisi) /3
print ("El alumno " +nombre + " " +apellido+ " "+" tiene como promedio: " +str(prom) )
if prom >6:
print("El alumno aprobo")
if prom >9:
print("Alumno destacado")
elif prom >=4:
print("A recuperatorio")
else:
print("Insuficiente")
|
250551b54b46542f2715fd50d08d0b50b3dfb6e2 | emlynazuma/leetcode-dalico | /290wordPattern.py | 454 | 3.5 | 4 | class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
_s = s.split(" ")
if len(pattern) != len(_s):
return False
seen = {}
seen_r = {}
for p, c in zip(pattern, _s):
if p not in seen:
seen[p] = c
if c not in seen_r:
seen_r[c] = p
if seen[p] != c or seen_r[c] != p:
return False
return True
|
2a0e449339b04888eab179e05946b4d5bebec81a | wraikes/pythonds | /ch_1/ex_14.py | 1,864 | 3.546875 | 4 | import random
class Card:
def __init__(self, suit, num):
self.suit = suit #heart; diamond; club; spade
self.num = num #2-10, J, Q, K, A
class Deck(Card):
def __init__(self):
self.deck = []
self.suits = ['H', 'D', 'C', 'S']
self.nums = [str(i) for i in range(2,11)] + ['J', 'Q', 'K', 'A']
def populate_deck(self):
for s in self.suits:
for n in self.nums:
self.deck.append(Card(s, n))
class War:
def __init__(self, Decka, Deckb):
self.player_a = 0
self.player_b = 0
self.Decka = Decka
self.Deckb = Deckb
def convert_card(self, card):
value = 0
if card.num == 'J':
value = 11
elif card.num == 'Q':
value = 12
elif card.num == 'K':
value = 13
elif card.num == 'A':
value = 14
else:
value = int(card.num)
return value
def round(self):
deck_size = len(self.Decka.deck)
#pull random int
ran_a = random.randint(0, deck_size-1)
ran_b = random.randint(0, deck_size-1)
#pop card
card_a = self.Decka.deck.pop(ran_a)
card_b = self.Deckb.deck.pop(ran_b)
#convert card into value
card_a_val = self.convert_card(card_a)
card_b_val = self.convert_card(card_b)
#score
if card_a_val < card_b_val:
self.player_b += 1
elif card_a_val > card_b_val:
self.player_a += 1
else:
print('It is a tie.')
print('Score player A: {}, B: {}'.format(self.player_a, self.player_b), end='\n\n')
if __name__=='__main__':
d1 = Deck()
d1.populate_deck()
d2 = Deck()
d2.populate_deck()
war = War(d1, d2)
for i in range(20):
war.round()
|
05c7ec1410234df904791559cf5353622dfe7cb6 | Capoqq/InteligenciaComputacional | /primer taller/punto23.py | 880 | 4.09375 | 4 | dineroInicial = 1000000
compra = int(input("De cuento es el valor de su compra: "))
if compra < 500:
dineroInvertido = compra*0.7
credito = compra*0.3
interes = credito*0.2
print(f"Esta es la cantidad de dinero a invertir {dineroInvertido} ")
print(f"Este es el valor del credito { credito }")
print(f"Este es el valor del interes {interes}")
elif compra > 500000:
dineroInvertido = compra*0.55
prestamo = compra*0.3
credito = compra*0.15
interes = credito*0.2
print(f"Esta es la cantidad de dinero a invertir {dineroInvertido}")
print(f"Este es el valor del prestamo {prestamo}")
print(f"Este es el valor del credito {credito}")
print(f"Este es el interes del credito {interes}")
elif compra >= 500 and compra < 500000:
dineroInvertido = compra
print(f"La empresa paga todo el valor de la compra {dineroInvertido}") |
281b2cb47ab2c3fa7fcf47f454268689c87367ec | HenryDavidZhu/PyGame-Space-Invaders | /spaceinvaders.py | 5,421 | 3.84375 | 4 | '''
PyGame remake of Space Invaders
Author: Henry Zhu
Date: 07/18/16
'''
from pygame import *
import random
import sys
class Sprite:
'''
A Sprite class that can initialize a sprite based on an image, and display it.
Parameters:
filename -> the path of the image to be used
xpos -> the x position of the sprite
ypos -> the y position of the sprite
'''
def __init__(self, filename, xpos, ypos):
self.xpos = xpos
self.ypos = ypos
self.sprite_image, self.rect = load_image(filename, (0, 0, 0))
self.sprite_image.set_colorkey((0, 0, 0))
def display(self, screen):
'''
Displays the sprite onto the screen.
Parameters:
screen -> the PyGame display to draw onto.
'''
screen.blit(self.sprite_image, (self.xpos, self.ypos))
def set_rect_attributes(self, x, y):
self.rect.left = x
self.rect.top = y
self.rect.right = x + self.rect.width
self.rect.bottom = y + self.rect.height
def intersect(self, sprite_2):
'''
Returns whether a sprite intersects with another sprite.
Parameters:
sprite_2 -> the sprite to compare intersection with
Returns:
Whether the sprite intersects with sprite_2
'''
return self.rect.colliderect(sprite_2.rect)
def load_image(path, colorkey):
'''
Returns an image and its bounding rectangle based on a filename.
Parameters:
path -> the path of the picture
colorkey -> the color defined to be transparent
Returns:
the loaded image
the bounding rectangle of the image
'''
try:
sprite_image = image.load(path)
except error, message:
print("Cannot load image: {0}".format(path))
sprite_image = sprite_image.convert()
if colorkey is not None:
if colorkey is -1:
colorkey = sprite_image.get_at((0, 0))
sprite_image.set_colorkey(colorkey, RLEACCEL)
return sprite_image, sprite_image.get_rect()
def main():
'''
The main function runs the Space Invader game, implementing all the logic, calculation,
and user interaction.
'''
init()
screen = display.set_mode((800, 600))
display.set_caption("Space Invaders")
fighter = Sprite("spaceship.png", 357, 520)
enemies = []
bullets_good = [] # List of all of the bullets fired by the hero / fighter
bullets_bad = []
for i in range(14): # Add the enemies into the enemies list
new_enemy = Sprite("enemy.png", 55 * i + 7, 30)
enemies.append(new_enemy)
while True:
screen.fill((0, 0, 0)) # Continiously refresh the background of the screen
if len(enemies) == 0: # The player wins the game
print("You win!")
quit()
sys.exit()
for enemy in enemies: # Draw the enemies onto the screen
enemy.set_rect_attributes(enemy.xpos, enemy.ypos)
enemy.display(screen)
selected_enemy = random.randint(0, len(enemies) - 1)
shoot_probability = random.randint(0, 20)
if shoot_probability == 5:
bullet_x = enemies[selected_enemy].xpos
bullet_y = enemies[selected_enemy].ypos
mixer.music.load("enemy_fire.wav")
mixer.music.play(0)
bad_bullet = Sprite("enemy_bullet.png", bullet_x + 17, bullet_y + 45)
bullets_bad.append(bad_bullet)
for bullet in bullets_good: # Draw the bullets onto the screen
bullet.ypos -= 10
bullet.set_rect_attributes(bullet.xpos, bullet.ypos)
for enemy in enemies:
if bullet.intersect(enemy) == 1:
# Play the sound effect of shooting a bullet
mixer.music.load("hit.wav")
mixer.music.play(0)
enemies.remove(enemy) # Remove the enemy from the list of enemies
bullet.display(screen)
for bad_bullet in bullets_bad:
bad_bullet.ypos += 10
bad_bullet.set_rect_attributes(bad_bullet.xpos, bad_bullet.ypos)
if bad_bullet.intersect(fighter) == 1:
print("You lose!")
quit()
sys.exit()
bad_bullet.display(screen)
for keyevent in event.get(): # Go through key press events
if keyevent.type == QUIT:
quit()
sys.exit()
if keyevent.type == KEYDOWN:
if keyevent.key == K_UP:
# Play the sound effect of shooting a bullet
mixer.music.load("fire.wav")
mixer.music.play(0)
# Create a new bullet and add it to the list of bullets fired by the hero
bullet = Sprite("bullet.png", fighter.xpos + 34, fighter.ypos - 20)
bullets_good.append(bullet)
keys = key.get_pressed()
if keys[K_LEFT] and fighter.xpos >= 0:
fighter.xpos -= 5
if keys[K_RIGHT] and fighter.xpos <= 800 - 85:
fighter.xpos += 5
fighter.set_rect_attributes(fighter.xpos, fighter.ypos)
fighter.display(screen)
display.update()
pass
main() # Run the game!
|
878f9f3e59bd52aa97d7dc5934e9f2e5a344538c | Almaz97/hackerrank | /basic_data_type/nested_lists.py | 720 | 3.859375 | 4 | from operator import itemgetter
if __name__ == '__main__':
students = [["Harry", 23.3], ["Benny", 23.3], ["Almaz", 32.3], ["Sarah", 11.1]]
# for _ in range(int(input())):
# name = input()
# score = float(input())
# students.append([name, score])
students.sort(key=itemgetter(1), reverse=True)
lowestGrade = students[0][1]
secondLowestGrade = students[0][1]
for liElem in students:
if liElem[1] < lowestGrade:
secondLowestGrade, lowestGrade = lowestGrade, liElem[1]
names = []
for liElem in students:
if liElem[1] == secondLowestGrade:
names.append(liElem[0])
names.sort()
for name in names:
print(name)
|
dde8d8bdacad05c4b95acad74b66a02168095376 | shrikantayya/shrigh | /fuction.py | 170 | 3.609375 | 4 | def main():
a=eval(input("enter the number"))
while not(a<0):
print(list((range(a))))
break
else:
print("error")
main() |
ecb20e18ee8a637d44e24d9ba9a89d3cb52799a7 | Wave1994-Hoon/data-structure-study-using-python | /Queue1/QueueWithNode.py | 991 | 3.96875 | 4 | class Node(object):
def __init__(self, value=None, next=None):
self.value = value
self.next = next
class LinkedQueue(object):
def __init__(self):
self.head = None
self.tail = None
self.count = 0
def isEmpty(self):
return not bool(self.head)
def enqueue(self, value):
node = Node(value)
if not self.head:
self.head = node
self.tail = node
else:
if self.tail:
self.tail.next = node
self.tail = node
self.count += 1
def dequeue(self):
def size(self):
def peek(self):
def __repr__(self):
if __name__ == "__main__":
queue = LinkedQueue()
print(f"is empty Queue ?: {queue.isEmpty()}")
for i in range(5):
queue.enqueue(i)
print(f"Queue: {queue}")
print(f"Queue size: {queue.size()}")
print(f"peek: {queue.peek()}")
queue.dequeue()
print(f"Queue: {queue}")
|
6c0a6fdb8572cd5dce58fd25c4d2cb26dd064172 | venkatesh799/DataStructures-Algorithms | /Hackerrank/Two Strings.py | 600 | 3.9375 | 4 | '''
Given two strings, determine if they share a common substring. A substring may be as small as one character.
For example, the words "a", "and", "art" share the common substring a . The words "be" and "cat" do not share a substring.
Sample Input :
2
hello
world
hi
world
Sample Output :
YES
NO
'''
def twoStrings(s1, s2):
a1="YES"
a2="NO"
k=set(s1).intersection(s2)
if len(k) > 0:
return a1
else:
return a2
n=int(input())
for x in range(n):
s1=input().strip()
s2=input().strip()
s1=list(s1)
s2=list(s2)
res=twoStrings(s1,s2)
print(res)
|
5e9d2ab9b98beefe93b7a7827c1365ddf893b978 | pecet/pytosg | /TwitterStatsLib/InsertableOrderedDict.py | 1,030 | 3.640625 | 4 | """ Simple module to add InsertableOrderedDict, variant of OrderedDict with insertafter method """
# pylint: disable=E1101
# disable error while accessing private member of OrderedDict
from collections import OrderedDict
class InsertableOrderedDict(OrderedDict):
""" OrderedDict extending class which adds method to insert new key at arbitary position """
def insertafter(self, afterkey, key, value, dict_setitem=dict.__setitem__):
# Each link is stored as a list of length three: [0=PREV, 1=NEXT, 2=KEY].
if afterkey is not None:
if afterkey not in self:
raise KeyError('Cannot insert new value after not-existing key \'{0}\''.format(afterkey))
node = self._OrderedDict__map[afterkey]
else:
node = self._OrderedDict__root
node_next = node[1]
if key in self:
del self[key]
node[1] = node_next[0] = self._OrderedDict__map[key] = [node, node_next, key]
dict_setitem(self, key, value)
|
0758a2baf2301e67c2c21425151793f820a223d4 | fahmoreira/L-Python | /cursoemvideo/repo/mundo1/ex021.py | 182 | 3.609375 | 4 | print('==== Desafio 21 ====')
#Faça um programa em Python que abra e reproduza o áudio de
# um arquivo MP3.
from playsound import playsound
playsound(r"C:\\temp\\Calvin.mp3")
|
95d1a6491b9c41adf6b043a1dfda0bc2b39fd38e | fzingithub/SwordRefers2Offer | /4_LEETCODE/1_DataStructure/5_Tree/1_BinaryTree/遍历/层次/JZ32_从上到下打印二叉树.py | 605 | 3.625 | 4 | class TreeNode:
def __init__(self, value):
self.val = value
self.left = None
self.right = None
class Soluton:
def PrintFromTopToBottom(self, pRoot):
'''
借助队列
:param pRoot:
:return: List
'''
if not pRoot:
return []
Queue = [pRoot]
res = []
while Queue:
pNode = Queue.pop(0)
res.append(pNode.val)
if pNode.left:
Queue.append(pNode.left)
if pNode.right:
Queue.append(pNode.right)
return res
|
eb9651d9844134f7cbf28fff5e49ddf062110ef1 | he44/Practice | /leetcode/2020_08_challenge/0808_closest_bst_value.py | 707 | 3.796875 | 4 | from typing import *
# 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 closestValue(self, root: TreeNode, target: float) -> int:
closest = root.val
cur = root
while cur:
# update closest
new_diff = abs(cur.val - target)
closest = cur.val if new_diff < abs(closest - target) else closest
# binary search
if cur.val > target:
cur = cur.left
else:
cur = cur.right
return closest
|
98449a278ca1a48a6a133d5e973f5d1b0ca72512 | shifelfs/shifel | /1.py | 285 | 3.5 | 4 | //print the max occurence of number and the number by concatenating the list
l=list(input().split())
a=""
b=[]
for i in l:
a=a+i
for i in range(0,10):
i=str(i)
c=a.count(i)
b.append(c)
m=max(b)
print(m)
for i in range(0,10):
if b[i]==m:
print(i,end=" ")
|
f7f50dbf79380944d492a966b0cbbf0c6e952b31 | kleberandrade/uri-solutions-python-3 | /uri1002.py | 212 | 3.859375 | 4 | # define o valor de pi conforme o problema
pi = 3.14159
# lê a entrada (raio do circulo)
raio = float(input())
# calcula a área do circulo
area = pi * (raio**2)
# exibe o resultado
print ("A=%.4f" % (area)) |
ce14097efe3622d36caf1d1a2f8c9d523c068fb7 | DamienAllonsius/deep_control | /main.py | 1,644 | 3.96875 | 4 | """
Author : Damien Allonsius & Simone Totaro
Date : 29/11/2018
Python Version : 3.6
Main function for deep control.
Take a PDE equation (for example parabolic)
and discretize it. For the moment : dimension space = 1.
The code works this way:
_ Select an initial condition on the mesh
_ Take a random control v
_ Take epsilon >0
_ While error(v) > epsilon do:
_ Inject in the system a control v : you get the solution at time T : y(T).
_ Third you compute the loss function : error(v) = y^2(T) (for the moment).
_ Finally you use a Neural Network to compute a better control.
"""
import numpy as np
from neural_network import *
from mesh import *
from equation import *
from test_case import *
test_case = TEST_CASE_1
x_uniform = np.linspace(test_case['DOMAIN'][0], test_case['DOMAIN'][1], test_case['POINT_X'])
mesh = Mesh(x = x_uniform)
# Intialise the equation control
equation = Equation(test_case, mesh)
neural_network = Neural_network(equation.get_loss_value())
count = 0
while neural_network.loss_value > test_case['EPSILON']:
count += 1
# update the control variable of the equation
# equation.control = neural_network.one_step_improvement(equation.control)
# update the y variable of equation by computing the solution with the new control
equation.compute_solution()
# use the loss function to compute the loss value
loss = equation.get_loss_value()
# print the result
print('iteration : ' + str(count) + '. Loss value: ' + str(loss))
# update the loss value of the neural network
neural_network.loss_value = loss
# plot the solution
user_interface = UI(test_case, mesh, equation.y)
|
40ddc4c2d50386dad8848775201bdf454db2cc9e | shadowstep666/phamminhhoang-labs-c4e25 | /labs3/homework/f-math-problem/freakingmath.py | 571 | 3.59375 | 4 | from random import *
from calc import eval
def generate_quiz():
# Hint: Return [x, y, op, result]
x=randint(0,9)
y=randint(1,9)
error=randint(-1,1)
op=choice(["+","-","*","/"])
result=eval(x, y,op) + error
return [x, y, op, result]
def check_answer(x, y, op, result, user_choice):
if user_choice == True:
if result == eval(x, y, op):
return True
else:
return False
elif user_choice == False:
if result == eval(x, y, op):
return False
else:
return True
|
7389f37d48a1da47b0d589ad33bdce627437bc73 | robinyms78/My-Portfolio | /Exercises/Python/Learning Python_5th Edition/Chapter 4_Introducing Python Object Types/Examples/Dictionaries/Missing Keys/Example3/Example3/Example3.py | 168 | 3.796875 | 4 | D = {"a": 1, "b": 2, "c": 3}
# Index but with a default
value = D.get("x", 0)
print(value)
# if/else expression form
value = D["x"] if "x" in D else 0
print(value) |
f6101ade3db39ef2656af5e50efc30373890221d | PDXCodeGuildJan/KatieCGBootcamp | /book_work_through.py | 349 | 4.0625 | 4 | def temp_converter():
celsius = eval(input("What is the Celsius temperature? "))
fahrenheit = 9/5 * celsius + 32
print("The temperature is", fahrenheit, "degrees fahrenheit. :)")
calculator()
def calculator():
answer = eval(input("Enter an expression: "))
print(answer)
def fact(n):
if n == 0:
return 1
else:
return n *fact(n-1)
|
023cc1ff4de2107c91ddae8dc32b7fb9f9e31eb3 | Tech-Amol5278/Python_Basics | /c19 - working with OS/os module part-2.py | 719 | 3.8125 | 4 | # OS module part 2
# to get the folder-subfolders and files from given directory
import os
import shutil
x_dir = os.walk(r'D:\amol_lap_data\python_tutor')
for current_path,folder_names,file_names in x_dir:
print(f'current path: {current_path}')
print(f'folder name: {folder_names}')
print(f'file name: {file_names}')
## to create directory in working directory
print(os.getcwd())
os.makedirs(r'movies\movie-1')
# to delete the directory
# os.rmdir('songs') # Deletion only happens only if the directory is empty
# to remove the directory tree
shutil.rmtree('movies')
# to copy the tree
shutil.copytree('','')
# to copy files
shutil.copy('','')
# to move a file or folder
shutil.move('','')
|
84d5545cc7a794a73a3cd368995000d17403d0ca | JetCrazy/cs | /python/1.3.5.py | 254 | 3.53125 | 4 | def how_eligible(essay):
count = 0
if "?" in essay:
count = count + 1
if "," in essay:
count = count + 1
if "!" in essay:
count = count + 1
if "\"" in essay:
count = count + 1
print(count) |
a0e3be65c412ec412191263e0f02848d372f3204 | henryji96/LeetCode-Solutions | /Easy/690.employee-importance/employee-importence2.py | 801 | 3.65625 | 4 | """
# Employee info
class Employee:
def __init__(self, id, importance, subordinates):
# It's the unique id of each node.
# unique id of this employee
self.id = id
# the importance value of this employee
self.importance = importance
# the id of direct subordinates
self.subordinates = subordinates
"""
class Solution:
def getImportance(self, employees, id):
"""
:type employees: Employee
:type id: int
:rtype: int
"""
employeeDict = {e.id: e for e in employees}
def dfs(id):
actualEmp = employeeDict[id]
subImportance = sum([dfs(subID) for subID in actualEmp.subordinates])
return subImportance + actualEmp.importance
return dfs(id)
|
5e0b5663909a0f778bffa354c3452ff982fc61fe | AneervanCoder/Data-Science-and-Machine-Learning | /Pandas/delete_column.py | 615 | 3.671875 | 4 | import pandas as pd
mydict = {'names': ['Somu', 'Kiku', 'Amol', 'Lini'],
'physics': [68, 74, 77, 78],
'chemistry': [84, 56, 73, 69],
'algebra': [78, 88, 82, 87] }
s=pd.Series(mydict)
print(s)
print("#########################")
#create dataframe
df_marks = pd.DataFrame(mydict)
print('Original DataFrame\n--------------')
print(df_marks)
print("########after pop###############")
df1=df_marks
#delete column
df1.pop("algebra")
print('\n\nDataFrame after deleting column\n--------------')
print(df1)
print("########last###############")
print(df_marks)
|
7782abbda92e41b3f7f911e7fc709aa4b3b75112 | jainanuj261/hack_2020 | /check_parenthesis.py | 750 | 3.9375 | 4 | def areParanthesisBalanced(expr):
stack = []
for char in expr:
if char in ["[", "(", "{"]:
stack.append(char)
else:
if not stack:
return False
curr_char = stack.pop()
if curr_char == '(':
if char != ')':
return False
if curr_char == '[':
if char != ']':
return False
if curr_char == '{':
if char != '}':
return False
if stack: # check if stack is not empty
return False
return True
if areParanthesisBalanced("()("):
print('Balan')
else:
print("Unbalan")
# Hi from github!!
|
131c1698f960bef0eebdea533381a16f20287f0f | MylesAustin13/normal-repo | /03/piglatin.py | 353 | 3.921875 | 4 | def piglatinify(str):
format = ""
if(str[0] == "a" or str[0] == "e" or str[0] == "i" or str[0] == "o" or str[0] == "u"):
format = str + "ay"
else:
format = str[1:] + str[0] + "ay"
return format
testA = piglatinify("thumb")
print(testA)
testB = piglatinify("apple")
print(testB)
testC = piglatinify("kitten")
print(testC) |
bcf046eda87272fe3d9961f4f586f6af0eab97d7 | bermec/python | /src/projectmodules/text_file.py | 1,495 | 3.671875 | 4 | #-------------------------------------------------------------------------------
# Name: module2
# Purpose:
#
# Author: rog
#
# Created: 02/08/2010
# Copyright: (c) rog 2010
# Licence: <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python
import sys
sys.path.append("../")
from rogutil import *
from pprint import pprint
def doif(lst, a,b,c,str_upper,str_lower):
mylist = list(lst)
if mylist [str_lower] [b] > mylist [str_lower] [c]:
mylist[str_upper][a] = mylist[str_upper][a] + mylist[str_lower][b]
else:
mylist[str_upper][a] = mylist[str_upper][a] + mylist[str_lower][c]
return mylist
def main():
pass
text_file = open("triangle.txt", "r")
mytext = text_file.readlines()
print(mytext)
mylist = []
for item in mytext:
mylist.append(list(map(int,item.split(" "))))
print(mylist)
#import pdb; pdb.set_trace()
'''start at the bottom two rows'''
str_upper, str_lower = len(mylist[-1])-2,len(mylist[-1])-1
e = len(mylist[str_upper])
a, b, c, d = 0, 0, 1, 0
while e != 0:
while d in range(0,e,1):
mylist = doif(mylist,a,b,c, str_upper, str_lower)
a += 1
b += 1
c += 1
d += 1
d, a, b, c = 0, 0, 0, 1
str_upper -=1
str_lower -=1
e -= 1
print(mylist[0])
exit()
if __name__ == '__main__':
main()
|
2741bc9859de0398494f1bed32d2f224ad5fb9d0 | LizinczykKarolina/Python | /Algorithms/ex8.py | 120 | 3.6875 | 4 | #8. Write a Python program to sort a list of elements using the merge sort algorithm.
def merge_sort(a_list, l, r):
|
f86e5b5a9f86e0b0d7a5b71c715718b47be4f761 | andrew-uwb/TripleDES | /3Des.py | 23,783 | 3.59375 | 4 | #!/usr/bin/python3
import sys
import random
#for bit manipulation
from bitstring import BitArray
#for initial password hash
from Cryptodome.Hash import SHA256
#This class contains all the methods used for encrypting and decrypting with triple DES,
#as well as the methods for generating the key file. Below this class is the code
#that actually takes in input from the command line and calls this class.
class des:
#Various items stored as class variables. This may be an artifact of my early days
#as a Java programmer, but in certain cases I preferred to use a class variable
#rather than pass lots of variables back and forth between methods. If this were
#"production", I feel like I would probably want to take more steps to obscure or hide the
#key when it's in memory, but for this, I decided not to worry about that part.
def __init__(self):
self.key = BitArray()
self.roundKeys = list()
self.setLookupTables()
#I set most of the lookup tables as class variables so that I only have to do it once, on
#instantiation of the class, and they're accessible across methods.
def setLookupTables(self):
#This is the initial permutation of the key
self.INITIAL_P = [58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
63, 55, 47, 39, 31, 23, 15, 7]
#Permutation to be used to generate each 48-bit key
self.ROUND_P = [14, 17, 11, 24, 1, 5, 3, 28,
15, 6, 21, 10, 23, 19, 12, 4,
26, 8, 16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55, 30, 40,
51, 45, 33, 48, 44, 49, 39, 56,
34, 53, 46, 42, 50, 36, 29, 32]
#Left shift to be applied to each of the sixteen round keys
self.roundShift = [1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1]
#The eight DES S-Boxes
self.S_BOX = [
[[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7],
[0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8],
[4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0],
[15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13],
],
[[15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10],
[3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5],
[0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15],
[13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9],
],
[[10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8],
[13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1],
[13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7],
[1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12],
],
[[7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15],
[13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9],
[10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4],
[3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14],
],
[[2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9],
[14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6],
[4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14],
[11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3],
],
[[12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11],
[10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8],
[9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6],
[4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13],
],
[[4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1],
[13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6],
[1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2],
[6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12],
],
[[13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7],
[1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2],
[7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8],
[2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11],
]
]
#Expansion permutation used to expand a 32-bit segment to 48 bits
self.EXPANSION_P = [32, 1, 2, 3, 4, 5,
4, 5, 6, 7, 8, 9,
8, 9, 10, 11, 12, 13,
12, 13, 14, 15, 16, 17,
16, 17, 18, 19, 20, 21,
20, 21, 22, 23, 24, 25,
24, 25, 26, 27, 28, 29,
28, 29, 30, 31, 32, 1]
#P-Box Permutation
self.P_BOX = [16, 7, 20, 21, 29, 12, 28, 17,
1, 15, 23, 26, 5, 18, 31, 10,
2, 8, 24, 14, 32, 27, 3, 9,
19, 13, 30, 6, 22, 11, 4, 25]
self.P_FINAL = [40, 8, 48, 16, 56, 24, 64, 32,
39, 7, 47, 15, 55, 23, 63, 31,
38, 6, 46, 14, 54, 22, 62, 30,
37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28,
35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26,
33, 1, 41, 9, 49, 17, 57, 25]
#Function to permute the bits of a starting array based on a given lookup table
def permuteBits(self, inputBits, table):
permuted = BitArray()
count = 0
#Go through the lookup table in order
for x in table:
#And append the bit at the given location of the initial array
permuted.append(inputBits[(x - 1):x])
count = count + 1
#At the end, you have an array of bits permuted as dictated by the lookup table
return permuted
#Method to create the keyfile from an initial 192-bit key
#The 192-bit key contains the 3 starting 64-bit keys in sequential order
def createKeyFile(self, initialKey, filename):
#Lookup table to be used in permuting the key from 64 to 56 bits
#In "real" DES, the deleted bits are parity-checking bits, but this is
#just a demo/simulation.
KEY_P = [57, 49, 41, 33, 25, 17, 9,
1, 58, 50, 42, 34, 26, 18,
10, 2, 59, 51, 43, 35, 27,
19, 11, 3, 60, 52, 44, 36,
63, 55, 47, 39, 31, 23, 15,
7, 62, 54, 46, 38, 30, 22,
14, 6, 61, 53, 45, 37, 29,
21, 13, 5, 28, 20, 12, 4]
keyCount = 0
keyWriter = open(filename, 'w')
#Loop 3 times, each time taking the next 64-bit key and permuting it the 56-bit DES key
while keyCount < 192:
subKey = initialKey[keyCount:(keyCount + 64)]
subKey = self.permuteBits(subKey, KEY_P)
#After permuting, write 56-bit key to the keyfile
#Written as a string of 1s and 0s rather than a literal bit sequence to aid in debugging
keyWriter.write(subKey.bin)
keyCount = keyCount + 64
keyWriter.closed
#Method to read in the keyfile, where the keyfile is a string of 168 0s and 1s
def readKeyFile(self, filename):
keyReader = open(filename, 'r')
self.key = BitArray(bin=keyReader.read())
#Method to generate 16 round keys, based on an initial 56-bit key
def roundKeyGen(self, initialKey, operation):
cKey = BitArray()
dKey = BitArray()
self.roundKeys = list()
for roundCount in range(0,16):
#Split 56-bit key into C and D
cKey = initialKey[0:28]
dKey = initialKey[28:56]
#Rotate to the left by the amount appropriate for each round
cKey.rol(self.roundShift[roundCount])
dKey.rol(self.roundShift[roundCount])
#Put them back together for the 56-bit key
cKey.append(dKey)
initialKey = cKey
#The 48-bit permutation is calculated and stored in the list of round keys
#The 56-bit key is kept and saved to calculate the next round key
self.roundKeys.append(self.permuteBits(initialKey, self.ROUND_P))
#If we're doing a decryption we need to run the round keys in reverse order.
if (operation == 'DECRYPT'):
roundKeyReversal = list()
i = 0
for i in range(0,16):
roundKeyReversal.append(self.roundKeys[15 - i])
self.roundKeys = roundKeyReversal
def encrypt(self, infile, outfile, mode):
#If encryption, we run the triple DES algorithm with operation set to 'ENCRYPT'
self.runTripleDes(infile, outfile, mode, 'ENCRYPT')
def decrypt(self, infile, outfile, mode):
#If decryption, we run the triple DES algorithm with operation set to 'DECRYPT'
self.runTripleDes(infile, outfile, mode, 'DECRYPT')
def runTripleDes(self, infile, outfile, mode, operation):
inputRead = open(infile, 'r')
stringToProcess = inputRead.read()
#If reading from unencrypted text file, then file input will be a standard string
#Otherwise it will be a hex string
if (operation == 'ENCRYPT'):
inputBits = BitArray(bytes=stringToProcess.encode('utf8'))
inputBits = self.bufferInput(inputBits)
elif (operation == 'DECRYPT'):
inputBits = BitArray(hex=stringToProcess)
#If decrypting, you will need to use the last key (K3) and the first key (K1) third.
#So just reverse the order of the 3 56-bit subkeys in the overall 168-bit key.
#
#This does not apply to OFB, which treats encryption and decryption the same.
if (mode != 'OFB'):
keyReverse = BitArray()
j = 0
for j in range(0,3):
readFrom = 112 - (j*56)
keyReverse.append(self.key[readFrom:(readFrom + 56)])
self.key = keyReverse
#position will track our progress through the input bits
position = 0
#outputBits is where we're going to store the finished output and will
#eventually write it to the output file.
outputBits = BitArray()
#For CBC and OFB modes we need to set an initialization vector.
if (mode != 'ECB'):
#If encrypting, generate a new 64 bit random string.
if (operation == 'ENCRYPT'):
#xorVector will store the initialization vector here
#During triple DES it will keep storing the value to use for XORing in the next round
xorVector = BitArray()
#Leaving the seed argument blank seeds rand with the time
random.seed()
randomNum = random.getrandbits(64)
#Convert random integer to 64-bit bitstring
xorVector = BitArray(uint = randomNum, length=64)
#Append to the beginning of the output string, so IV will be the first
#64 bits of the file
outputBits.append(xorVector)
elif (operation == 'DECRYPT'):
#If decrypting, the first 64 bits of the input is the IV. Read in, store,
#and delete it from the input.
xorVector = inputBits[0:64]
del inputBits[:64]
#This is the loop that actually cycles through each 64 bits of the input.
while position < inputBits.length:
#unProcessedBits stores the next 64 bit input from the file.
#It's plaintext if encrypting, ciphertext if decrypting.
unprocessedBits = inputBits[position:(position + 64)]
#If CBC our input into the encryption will be the XOR Vector from the previous round
#(or IV if the first round) XORed with the plaintext from file
if (mode == 'CBC'):
if (operation == 'ENCRYPT'):
segmentInput = unprocessedBits ^ xorVector
#For CBC decryption our input into the encryption is ciphertext
else:
segmentInput = unprocessedBits
#In OFB mode (encryption or decryption) input is the result of the XOR from the previous round.
elif (mode == 'OFB'):
segmentInput = xorVector
#In ECB mode (encryption or decryption), our input just the plaintext (encryption) or ciphertext (decryption)
else:
segmentInput = unprocessedBits
#If OFB, decryption runs the same as encryption.
if (mode == 'OFB'):
processedBits = self.tripleDesSegment(segmentInput, 'ENCRYPT')
#Else let the triple DES algorithm know if it's encrypting or decrypting
else:
#The triple DES segment method is what actually does the round key
#generation and processing for each 64 bit segment
processedBits = self.tripleDesSegment(segmentInput, operation)
#For OFB mode
if (mode == 'OFB'):
#The output from this round of 3DES is stored as the XOR vector for the next round
xorVector = processedBits
#Final output of this cycle is an XOR of the 3DES output and the
#unprocessed file input (plaintext if encrypting, ciphertext if decrypting).
segmentOutput = unprocessedBits ^ processedBits
#For CBC mode
elif (mode == 'CBC'):
#On encryption, both final output (ciphertext) and XOR vector for next round are the
#output from this round of 3DES.
if (operation == 'ENCRYPT'):
xorVector = processedBits
segmentOutput = processedBits
#For decryption, final output is an XOR of output from this round of 3DES
#and ciphertext from previous round.
if (operation == 'DECRYPT'):
segmentOutput = processedBits ^ xorVector
#For next round, store xorVector as ciphertext from this round
xorVector = unprocessedBits
#If ECB
else:
#Final output is the direct output from 3DES algorithm
segmentOutput = processedBits
#Append final output to string of output bits
outputBits.append(segmentOutput)
#Increment position for the next round of 3DES
position = position + 64
#After 3DES is done, write output
outputWriter = open(outfile,'w')
#If the overall operation was an encrypt, we're writing out an encrypted hex string
if (operation == 'ENCRYPT'):
outputWriter.write(outputBits.hex)
#If the overall operation was a decrypt, we're writing out a cleartext string.
elif (operation == 'DECRYPT'):
#Remove the buffer that was originally added to make sure the input
#was divisible by 64 bits
bitsToProcess = self.removeBuffer(outputBits)
outputWriter.write((bitsToProcess.bytes).decode('utf8'))
#Runs Triple DES on a given bit string, for the given operation and mode.
def tripleDesSegment(self, bitsToProcess, oper):
i = 0
#For Triple DES, repeat the DES process 3 times
for i in range(0,3):
#Grab the next 56-bit portion of the 168-bit key.
stepKey = self.key[(56 * i):((56 * i) + 56)]
#Generate the 16 48-bit round keys off the 56-bit key
self.roundKeyGen(stepKey, oper)
#Run DES on the input string. The keys are stored in class variables, and set
#in the appropriate order for encryption or decryption by the generator method.
bitsToProcess = self.runSixteenRounds(bitsToProcess)
#Flip between encryption and decryption on every round but the last
if (i != 2):
if (oper == 'ENCRYPT'):
oper = 'DECRYPT'
elif (oper == 'DECRYPT'):
oper = 'ENCRYPT'
return bitsToProcess
#Method to buffer the input string so the number of bits to encrypt is
#evenly divisible by 64
def bufferInput(self, inputBits):
length = inputBits.length
#Get the modulus of the input string length at 64
amtToBuffer = length % 64
#If length is not evenly divisible by 64, then the amount
#we need to buffer is actually (64 - modulus)
if (amtToBuffer > 0):
amtToBuffer = 64 - amtToBuffer
#Append the appropriate hex string based on the amount of buffer needed
if (amtToBuffer == 8):
inputBits.append('0x01')
elif (amtToBuffer == 16):
inputBits.append('0x0202')
elif (amtToBuffer == 24):
inputBits.append('0x030303')
elif (amtToBuffer == 32):
inputBits.append('0x04040404')
elif (amtToBuffer == 40):
inputBits.append('0x0505050505')
elif (amtToBuffer == 48):
inputBits.append('0x060606060606')
elif (amtToBuffer == 56):
inputBits.append('0x07070707070707')
return inputBits
#Method to remove hex buffer after decryption, if one is present
def removeBuffer(self, inputBits):
#Check the last byte. If it's part of a buffer, crop the necessary length
#from the string
testByte = inputBits[(inputBits.length - 8):inputBits.length]
if(testByte=='0x07'):
del inputBits[-56:]
elif(testByte=='0x06'):
del inputBits[-48:]
elif(testByte=='0x05'):
del inputBits[-40:]
elif(testByte=='0x04'):
del inputBits[-32:]
elif(testByte=='0x03'):
del inputBits[-24:]
elif(testByte=='0x02'):
del inputBits[-16:]
elif(testByte=='0x01'):
del inputBits[-8:]
return inputBits
#Method to process the next 64-bit segment of plaintext
def runSixteenRounds(self, inputBits):
#Do initial permutation on the plaintext
inputBits = self.permuteBits(inputBits, self.INITIAL_P)
#Split into L0 and R0
leftBits = inputBits[0:32]
rightBits = inputBits[32:64]
#Do 16 rounds of encryption/decryption
for roundCount in range(0,16):
#Permute the 32 bits of R0 into 48
expandedBits = self.permuteBits(rightBits, self.EXPANSION_P)
#XOR the right bits and the round key
result = expandedBits ^ self.roundKeys[roundCount]
#Run the SBoxes on the result of the right bits/round key XOR
result = self.sBoxes(result)
#Do a PBox permutation
result = self.permuteBits(result, self.P_BOX)
#XOR the result with the left side
result = result ^ leftBits
#Swap the left and right if it's not the last round
if (roundCount < 15):
leftBits = rightBits
rightBits = result
else:
leftBits = result
#After 16 rounds, concatenate left and right sides
cText = leftBits
cText.append(rightBits)
#Do final permutation
cText = self.permuteBits(cText, self.P_FINAL)
return cText
#Method to run the S-Box substitutions for a single round
def sBoxes(self, inputString):
outputString = BitArray()
sBoxIncrement = 0
#8 SBoxes
for sBoxIncrement in range(0,8):
#Take the next 6 characters of the input string
currentPos = sBoxIncrement * 6
currentBits = inputString[currentPos:(currentPos + 6)]
#The four inner bits are the column lookup
innerBits = currentBits[1:5]
#The two outer bits are the row lookup
outerBits = currentBits[0:1]
outerBits.append(currentBits[5:6])
#Find the correct substitution in the SBox and append the bit representation to the output string
nextSegment = BitArray(uint=self.S_BOX[sBoxIncrement][outerBits.uint][innerBits.uint],length=4)
outputString.append(nextSegment)
return outputString
#Option 1: Key Generation
if sys.argv[1] == 'genkey':
passwd = sys.argv[2]
#Hash the password using SHA256
hashObj = SHA256.new(passwd.encode("utf8"))
filename = sys.argv[3]
#For creating the keys, we will split the first 192 bits of the hash into 3 64-bit keys and discard the rest
bitHash = BitArray(hashObj.digest())
#Take a segment of the hash long enough to split into 3 64-bit keys
#(64 rather than 56 because I included the initial key permutation to remove
#parity bits. I know they're not really parity bits in this case, but I didn't
#realize we didn't need to do this until after I'd already implemented it. I left it in,
#since it didn't seem to be hurting anything.)
bitHash = bitHash[0:192]
#print(bitHash.hex)
desKeygen = des()
#Create key file given an initial key hash
desKeygen.createKeyFile(bitHash, filename)
#Option 2: 3DES Encryption
elif sys.argv[1] == 'encrypt':
infile = sys.argv[2]
keyfile = sys.argv[3]
outfile = sys.argv[4]
mode = sys.argv[5]
encrypter = des()
#Read in specified keyfile
encrypter.readKeyFile(keyfile)
#Run encryption
encrypter.encrypt(infile, outfile, mode)
#Option 3: 3DES Decryption
elif sys.argv[1] == 'decrypt':
infile = sys.argv[2]
keyfile = sys.argv[3]
outfile = sys.argv[4]
mode = sys.argv[5]
decrypter = des()
#Read in specified keyfile
decrypter.readKeyFile(keyfile)
#Run decryption
decrypter.decrypt(infile, outfile, mode)
else:
print("Invalid command line arguments")
|
6b02b7be2571d448479b64e57d0ba8678da10582 | Mihango/hello_python_udacity | /tuples.py | 272 | 3.609375 | 4 | # assigning tuples
dimension = 12, 14, 15
print(dimension)
# destructuring a tuple
length, width, height = dimension
print(f'length: {length} width: {width} height: {height} ')
# compare tuples
tuple_a = (1, 2)
tuple_b = 1, 2
print(f'{tuple_a == tuple_b} {tuple_a[0]}')
|
8b6e91c2a6f92097b74c0b2d471928adea9c6b31 | jgj9883/Data-Analysis | /데이터 분석 프로젝트/analyze/Numpy/Numpy_01.py | 615 | 3.734375 | 4 | import numpy as np
# 배열 가로 축으로 합치기
array1 = np.array([1,2,3])
array2 = np.array([4,5,6])
array3 = np.concatenate([array1, array2])
# print(array3.shape)
# print(array3)
# 배열 형태 바꾸기
array1 = np.array([1,2,3,4])
array2 = array1.reshape((2,2))
# 배열 세로 축으로 합치기
array1 = np.arange(4).reshape(1, 4)
array2 = np.arange(8).reshape(2, 4)
# print(array1)
# print(array2)
array3 = np.concatenate([array1,array2], axis=0)
print(array3)
#배열 나누기
# array = np.arange(8).reshape(2, 4)
# left ,right = np.split(array, [2], axis=1)
# print(left)
# print(right) |
ae779f7f29a3c7c2d11e9ba5d1836afaa0b540d9 | NeisserMS/Java-Course-UPAO | /Ejercicios Básicos - Python/Trabajo_Ejercicio8.py | 401 | 3.796875 | 4 |
precio_segundo = 0.25
horas = float(input("Ingrese la cantidad de horas: "))
minutos = float(input("Ingrese la cantidad de minutos: "))
segundos = float(input("Ingrese la cantidad de segundos: "))
total_segundos = horas*3600 + minutos*60 + segundos
costo_total = total_segundos*precio_segundo
print("Los segundos son ", total_segundos, "y el costo total es ", costo_total)
|
03e23adc290cfb44aa687b1361a191a4537eb161 | DahlitzFlorian/why-you-should-use-more-enums-in-python-article-snippets | /colour.py | 197 | 3.6875 | 4 | # color.py
from enum import Enum
class Colour(Enum):
RED = 1
GREEN = 2
BLUE = 3
c = Colour.RED
print(c)
print(c.name)
print(c.value)
print(c is Colour.RED)
print(c is Colour.BLUE)
|
2e3b6fe91e5f4db441dc821862f216c1c068edad | sandeepkumar8713/pythonapps | /26_sixthFolder/02_patching_array.py | 1,665 | 3.703125 | 4 | # https://leetcode.com/problems/patching-array/
# Question : Given a sorted integer array nums and an integer n, add/patch elements to the array such
# that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array.
# Return the minimum number of patches required.
#
# Example : Input: nums = [1,3], n = 6
# Output: 1
# Explanation: Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.
# Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].
# Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].
#
# Question Type : ShouldSee
# Used : We initialize reach with 1. We loop until reach equals n.
# While looping we keep adding elements to nums to reach.
# If reach is less than next element in nums, then we need a patch.
# Double reach and increment patch count.
# After loop return patch count.
# Logic :
# while reach <= n:
# if i < len(nums) and nums[i] <= reach:
# reach += nums[i], i += 1
# else:
# reach *= 2, patches += 1
# return patches
# Complexity : O(n)
def minPatches(nums, n):
patches = 0
reach = 1
i = 0
while reach <= n:
if i < len(nums) and nums[i] <= reach:
reach += nums[i]
i += 1
else:
reach *= 2
patches += 1
return patches
if __name__ == "__main__":
nums = [1, 3]
n = 6
print(minPatches(nums, n))
nums = [1, 5, 10]
n = 20
print(minPatches(nums, n))
nums = [1, 2, 2]
n = 5
print(minPatches(nums, n))
|
7e69a844edb608bb562ed0251d9fe54a3436cb50 | tikishabudin/pythonLessons | /day3functions.py | 825 | 3.640625 | 4 | def myFx():
print("This is my function")
def myFx2(dog, dog2, param3):
print("This is the dog: ", dog)
print("This is the other dog: ", dog2)
print("I'm not even sure what this is: ", param3)
print("-"*20)
def myFx3(param1 = "Something", param2 = "Hahahaha", param3 = 42):
print("This is param1: ", param1)
if(param2 == None):
print("Param 2 does not have a value")
else:
print("Param 2 is : ", param2)
print("Param 3:", param3)
print("-"*20)
myFx3(23)
myFx3("Tiki", 123)
myFx3(1,2,3)
myFx3("Allu", param3="Good boy!")
myFx3(param3=567890)
def myFx4(param1,param3,param2=None):
print("P1:", param1)
print("P2:",param2)
print("P3:",param3)
print("-"*20)
myFx4(param3=10,param1=10)
def myFx5(x,y):
return x**y
result = myFx5(2,63)
print(result) |
5a15bf5b7ba0bb0e5aad1ea98f66604072134e6c | alokjs89/DataScience_Assignment3 | /Acadgild_Datscience_Assignment3.py | 640 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 23 01:28:29 2018
@author: ALOK
"""
# This python code converts lowercase to uppercase and uppercase to lowercase
#Sample input
myinput = "AltERNating"
#Function that converts lowercase to uppercase and uppercase to lowercase
def switch_lowerupper(string):
output = ''
#iterated through each work in the string
for word in string:
#Checks if work is upper, if true converts to lower by parsing
if word.isupper():
output += word.lower()
else:
output += word.upper()
return output
print switch_lowerupper(myinput)
|
ecf94130999a2398f7261d9da9a35b62f42236a3 | vincentlambert/Codewars | /src/langton_s_ant.py | 2,651 | 3.71875 | 4 | def ant(grid, column, row, n, direction=0):
print("[init] grid : %s" % grid)
print("[init] column : %s" % column)
print("[init] row : %s" % row)
print("[init] n : %s" % n)
print("[init] direction : %s" % direction)
for i in range(0, n):
if (grid[row][column]) == 1:
# WHITE
grid[row][column] = 0
direction = (direction + 1) % 4
print("[white] direction : %s" % direction)
else:
# BLACK
grid[row][column] = 1
direction = abs((direction - 1) % 4)
print("[black] direction : %s" % direction)
column, row = forward(grid, column, row, direction)
print(grid)
return grid
def forward(grid, column, row, direction):
if direction == 0:
# NORTH
if row == 0:
# grid = [0] * len(grid[0]) + grid
grid.insert(0, [0] * len(grid[0]))
else:
row -= 1
if direction == 1:
# EAST
if column == len(grid[0]) - 1:
for i in range(0, len(grid)):
grid[i].append(0)
column += 1
if direction == 2:
# SOUTH
if row == len(grid) - 1:
grid.append([0] * (len(grid[0])))
row += 1
if direction == 3:
# WEST
if column == 0:
for i in range(0, len(grid)):
# grid[i] = [0] + grid[i]
grid[i].insert(0, 0)
else:
column -= 1
return column, row
import unittest
class TestStringMethods(unittest.TestCase):
def test_runner(self):
self.assertEqual(ant([[1]], 0, 0, 1, 0), [[0, 0]])
self.assertEqual(ant([[0]], 0, 0, 1, 0), [[0, 1]])
self.assertEqual(ant([[1]], 0, 0, 3, 0), [[0, 1], [0, 1]])
self.assertEqual(
ant([[0, 0, 0], [0, 0, 0], [0, 0, 0]], 2, 2, 10, 1),
[[0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 1], [0, 0, 0, 1]],
)
# [
# [0, 0, 1, 1, 0],
# [0, 0, 1, 0, 1],
# [1, 0, 0, 0, 0],
# [1, 1, 1, 1],
# [1, 1, 0, 0],
# ]
# [
# [0, 0, 1, 1, 0],
# [0, 0, 1, 0, 1],
# [1, 0, 0, 0, 0],
# [1, 1, 1, 0, 1],
# [0, 1, 1, 0, 0],
# ]
self.assertEqual(
ant([[1, 0, 1], [0, 1, 0], [1, 0, 1]], 0, 0, 20, 0),
[
[0, 0, 1, 1, 0],
[0, 0, 1, 0, 1],
[1, 0, 0, 0, 0],
[1, 1, 1, 0, 1],
[0, 1, 1, 0, 0],
],
)
if __name__ == "__main__":
unittest.main()
|
91717c7dc4c079fc6e6554449f1b822a776d0624 | David-Xiang/Online-Judge-Solutions | /210710/LCOF41.py | 1,617 | 3.9375 | 4 | # LeetCodeOffer 41
# Find Median from Data Stream
# Priority Queue
# large_half is small root heap
# small_half is large root heap and all of its elems are negative value
# large_half might store one more elem
from typing import List
import heapq
class MedianFinder:
def __init__(self):
"""
initialize your data structure here.
"""
self.large_half = []
self.small_half = []
def addNum(self, num: int) -> None:
if len(self.large_half) == len(self.small_half):
heapq.heappush(self.large_half, num)
else:
heapq.heappush(self.small_half, -num)
if len(self.small_half) == 0:
return
if self.large_half[0] < - self.small_half[0]:
large_root = heapq.heappushpop(self.large_half, -self.small_half[0])
heapq.heappushpop(self.small_half, -large_root)
def findMedian(self) -> float:
if len(self.large_half) == 0:
return 0
if len(self.large_half) == len(self.small_half):
return (self.large_half[0] - self.small_half[0]) / 2
return self.large_half[0]
# Your MedianFinder object will be instantiated and called as such:
# obj = MedianFinder()
# obj.addNum(num)
# param_2 = obj.findMedian()
def test1():
obj = MedianFinder()
obj.addNum(1)
obj.addNum(2)
print(obj.findMedian())
obj.addNum(3)
print(obj.findMedian())
def test2():
obj = MedianFinder()
obj.addNum(2)
print(obj.findMedian())
obj.addNum(3)
print(obj.findMedian())
if __name__ == "__main__":
test1()
test2() |
0ecec0b841a5f421d43fe31d4ab023f7260b99d7 | cpm205/Machine-Learning | /Udemy/ML A-Z/Machine_Learning_AZ_Template_Folder/Machine Learning A-Z Template Folder/Part 8 - Deep Learning/Section 40 - Convolutional Neural Networks (CNN)/my_cnn.py | 7,169 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 19 23:04:02 2018
@author: Derek
"""
#Part 1 - Building the CNN
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
# Initialising the CNN
classifier = Sequential()
# Step 1 - Convolution
#32 - Number of feature detectors or filters, also number of feature maps we want to create.
#Because one feature detector generates one feature map. By default, it is 64.
#3 - Number of rows in feature detector table
#3 - Number of columns in feature detector table.
#input_shape - Shape of input image in this case. This will convert different size
#of images into same format.
#64 and 64 - Dimension of 2d array in each channel. If you want to use 128*128, please run code using GPU.
#3 - color channel, 3 is for colored image, 1 is for black and white image.
#Bear in mind, if we use Theano backend rather than TensorFlow, the order for input_shape should be
#(3,64,64)
#activation = 'relu' - Reason to use relu:First, remove any negative pixes, second remove linearity from
#model.
classifier.add(Convolution2D(32, 3, 3, input_shape = (64, 64, 3), activation = 'relu'))
#Number of Params: 896 = filter:32 * row:3 * column:3 * last value in input_shape:3 + filter:32
classifier.summary()
# Step 2 - Pooling
#2*2 is smallest
classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Adding a second convolutional layer could increase accuracy
#No need to specify input_shape in second convolutional layer, because the input for this layer is
#result from previous MaxPooling.
classifier.add(Convolution2D(32, (3, 3), activation="relu"))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Step 3 - Flattening
classifier.add(Flatten())
#How many input nodes do we actually have in our input layer after flattening.
classifier.summary()
# Step 4 - Full connection
#input Layer
#output_dim = 128 - come from experiment
#No need to speccify the weight initialization function, it will use "uniform" by default.
classifier.add(Dense(output_dim = 128, activation = 'relu'))
#Output layer
#Output_dim = 1 - Because we are predicting dog or cat, so the node in output layer is 1.
classifier.add(Dense(output_dim = 1, activation = 'sigmoid'))
#Adding another fully connected layer could increase the accuracy
# Compiling the CNN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
# Part 2 - Fitting the CNN to the images
#Image classification requires a lot of images for training the model, in this case we only have 10000 images,
#which is not a lot. ImageDataGenerator will help us in this case, it will create mnay batches of
#our images and then each batch will apply some random transformations on a random selection
#of our images like rotating them, shifting them, flipping them. Eventually what we getting
#during the training is many diverse images inside these batches. This is technique is called
#Augmentation.
from keras.preprocessing.image import ImageDataGenerator
#solve "image file is truncated" issue
#from PIL import ImageFile
#ImageFile.LOAD_TRUNCATED_IMAGES = True
train_datagen = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True)
test_datagen = ImageDataGenerator(rescale = 1./255)
#target_size = (64, 64) - When we do convolution, we choose image input_shape is
#64* 64, therefore the our target_size has to be 64*64 as well. Sometime increase this number
#can increase the accuracy.
#class_mode = 'binary' - we ony have 2 categories:cat and dog, so mode is binary
training_set = train_datagen.flow_from_directory('dataset/training_set',
target_size = (64, 64),
batch_size = 32,
class_mode = 'binary')
test_set = test_datagen.flow_from_directory('dataset/test_set',
target_size = (64, 64),
batch_size = 32,
class_mode = 'binary')
#steps_per_epoch - number of images in training set
#validation_data- - number of images in testing set for validate the model
classifier.fit_generator(training_set,
steps_per_epoch = 8000,
epochs = 25,
validation_data = test_set,
validation_steps = 2000)
#if you want to use gpu+cpu to train the model, please use model below
#but batch_size needs to be changed to 64 or 128 or 256 or so on
#classifier.fit_generator(training_set,
# steps_per_epoch = 8000,
# epochs = 25,
# validation_data = test_set,
# validation_steps = 2000,
# use_multiprocessing = True,
# workers = 4)
#we can use code below to make prediction
#from keras.preprocessing import image as image_utils
#import numpy as np
#
#test_image = image_utils.load_img('test.jpg', target_size=(64, 64))
#test_image = image_utils.img_to_array(test_image)
#test_image = np.expand_dims(test_image, axis=0)
#
#classes = test_set.class_indices
#result = classifier.predict(test_image)
#
#if result[0][0] == 1:
# prediction = 'dog'
#else:
# prediction = 'cat'
#Here how you can do predictions with some cat pictures:
# Make predictions with some cat pictures
#from keras.preprocessing import image as image_utils
#import numpy as np
#predictions=[]
#for i in range(1, 1000):
# test_image = image_utils.load_img('dataset/training_set/cats/cat.{0}.jpg'.format(i), target_size=(64, 64))
# test_image = image_utils.img_to_array(test_image)
# test_image = np.expand_dims(test_image, axis=0)
# predictions.append(classifier.predict_on_batch(test_image)[0][0])
#Or you can predict one picture, cat [0] or dog[1].
# prediction on a new picture
#from keras.preprocessing import image as image_utils
#import numpy as np
#
#test_image = image_utils.load_img('dataset/new_images/dog_picture.jpg', target_size=(64, 64))
#test_image = image_utils.img_to_array(test_image)
#test_image = np.expand_dims(test_image, axis=0)
#
#result = classifier.predict_on_batch(test_image)
#how to get loss curve and accuracy curve ?
#history = model.fit(X, Y, validation_split=0.33, epochs=150, batch_size=10, verbose=0)
## list all data in history
#print(history.history.keys())
## summarize history for accuracy
#plt.plot(history.history['acc'])
#plt.plot(history.history['val_acc'])
#plt.title('model accuracy')
#plt.ylabel('accuracy')
#plt.xlabel('epoch')
#plt.legend(['train', 'test'], loc='upper left')
#plt.show()
## summarize history for loss
#plt.plot(history.history['loss'])
#plt.plot(history.history['val_loss'])
#plt.title('model loss')
#plt.ylabel('loss')
#plt.xlabel('epoch')
#plt.legend(['train', 'test'], loc='upper left')
#plt.show() |
6f01bda382ad3bb0fbeec369c65c8a85ac6007ec | arpita-ak/APS-2020 | /Hackerrank solutions/Medium- Climbing the Leaderboard.py | 987 | 3.921875 | 4 | """
Climbing the Leaderboard: https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem
"""
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the climbingLeaderboard function below.
def climbingLeaderboard(s, scores, a, alice):
uniq=[0]*(s+a)
j=0
for i in scores:
if i not in uniq:
uniq[j]=i
j+=1
print(uniq)
for i in range(a):
for k in range(j):
if uniq[k]<alice[i]<uniq[k+1]:
uniq[k+1]=alice[i]
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = int(input())
scores = list(map(int, input().rstrip().split()))
a = int(input())
alice = list(map(int, input().rstrip().split()))
result = climbingLeaderboard(s, scores, a, alice)
fptr.write('\n'.join(map(str, result)))
fptr.write('\n')
fptr.close()
|
f46b7eb87bf75c9b94bb5ba2da1a9da5ee064e97 | vitalyryzhkov/vitaly_ryzhkov | /home_work_14_17.py | 1,721 | 4.125 | 4 | # task_14
"""
def is_even(number):
result = number % 2
return result == 0
# if result == 0:
# return True
# else:
# return False
# print(type(is_even(5)))
print("Number is even?:", is_even(int(input("Enter any number: "))))
"""
# task_15
# from math import *
#
# x1 = 1
# x2 = 2
# y1 = 8
# y2 = 14
# r1 = 4
# r2 = 7
#
# def is_circles_intersect():
# distance_between_centers = sqrt(pow((x2 - x1), 2) + pow((y2 - y1), 2))
# result = distance_between_centers - (r1+r2)
# return result <= 0
# print("Is circles intersect?:", is_circles_intersect())
# task_16
first_train_speed = 50
second_train_speed = 70
first_train_time = 4 / first_train_speed
second_train_time = 6 / second_train_speed
if first_train_time < second_train_time:
print("Поезда не столкнутся")
else:
print("Поезда столкнутся")
# task_17
"""
from math import *
def solve_quadratic_equation(a, b, c):
diskr = pow(b, 2) - 4 * a * c
if diskr > 0:
x1 = (-b-sqrt(diskr))/(2*a)
x2 = (-b+sqrt(diskr))/(2*a)
elif diskr == 0:
x1 = x2 = (-b)/(2*a)
elif diskr < 0:
x1 = x2 = None
return x1, x2
a = int(input("Введите первый коэффициент квадратоного уравнения: "))
b = int(input("Введите второй коэффициент квадратоного уравнения: "))
c = int(input("Введите свободный член квадратоного уравнения: "))
print("Результат вычисления квадратного уравнения при a = %d, b = %d и c = %d равен: "
% (a, b, c), solve_quadratic_equation(a, b, c))
"""
|
18e22c5e90d26213b99b93223e15b21ef8611d1d | RoqueFM/TIC_20_21_1 | /suma_gauss.py | 390 | 3.75 | 4 | Python 2.7.18 (v2.7.18:8d21aa21f2, Apr 20 2020, 13:25:05) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> def suma_gauss():
n_final=input("Inserte nmero final: ")
suma_acumulada=0
for cont in range(0,n_final+1):
suma_acumulada=suma_acumulada+cont
print "Suma total = ", suma_acumulada
>>> suma_gauss()
|
f227e8830b1a31842ec2c0f632f3c481ea632666 | EmonMajumder/All-Code | /Python/PaintCalculator_Remix.py | 1,773 | 4.46875 | 4 | #Don't forget to rename this file after copying the template for a new program!
"""
Student Name: Emon Majumder
Program Title: IT Programming
Description: PaintCalculator_Remix
"""
#Paint Shop Calculator
#Program to calculate the number of gallons of paint required to paint a room, if provided the room dimensions
def main(): #<-- Don't change this line!
#Write your code below. It must be indented!
#Import the math class, for using ceiling rounding
import math
#Declare variable for # of sq. ft. covered by one gallon of paint
square_feet_per_gallon = 150.0
#Intro messages
print("Welcome to the Paint Shop!")
print("This program will help you calculate how many cans of paint you need to buy, based on the dimensions of your room.")
#INPUT
#Get Dimensions of the room
length = float(input("\nEnter the length of the room, in feet: "))
width = float(input("Enter the width of the room, in feet: "))
height = float(input("Enter the height of the room, in feet: "))
#PROCESSING
#Calculate the area of the walls
#Divide the area by 150 square feet and
#round number of gallons up to the nearest whole number
def gallons_of_paint (length, height, width):
totalArea = 2*height*(length+width)
gallons_of_paint = math.ceil(totalArea / square_feet_per_gallon)
print("\nThe total wall area of your room is {0} square feet.".format(totalArea))
return gallons_of_paint
gallons_of_paint= gallons_of_paint (length, height, width)
#OUTPUT - Display number of gallons needed
print("You will need {0} gallon(s) of paint. \n\nHappy Painting!".format(gallons_of_paint))
#Your code ends on the line above
#Do not change any of the code below!
if __name__ == "__main__":
main()
|
0ecc9f0ba6caae0aa78e00ad8a052e81aed75aaf | thabbott/prisoners-dilemma | /Telepath.py | 1,442 | 3.75 | 4 | from Prisoner import Prisoner
"""
Telepath: a Prisoner who can read (a limited number of opponents') minds
"""
class Telepath(Prisoner):
"""
Track opponents' first two moves and the round number
"""
def __init__(self):
self.iround = 1
self.opp_first_move = True
self.opp_second_move = True
"""
Strategy: defect on round 1, cooperate on round 2, and then
try to identify your opponent on subsequent rounds and play accordingly
"""
def pick_strategy(self):
if self.iround == 1:
return False
elif self.iround == 2:
return True
else:
if self.opp_first_move:
if self.opp_second_move:
# Assume Jesus and defect
return False
else:
# Assume TitForTat and defect
return False
else:
if self.opp_second_move:
# Assume Telepath and cooperate
return True
else:
# Assume Lucifer and defect
return False
"""
Record first two strategies
"""
def process_results(self, my_strategy, other_strategy):
if self.iround == 1:
self.opp_first_move = other_strategy
elif self.iround == 2:
self.opp_second_move = other_strategy
self.iround += 1
|
4d13996d26a3061d87231b2eaea467d4e264ec4c | Simplon-IA-Bdx-1/the-movie-predictor-nicoOkie | /utils.py | 250 | 3.921875 | 4 | def split_name(name):
name_list = name.split(" ")
for name in name_list:
firstnames = (len(name_list) - 1)
firstname = " ".join(name_list[:firstnames])
lastname = name_list[firstnames]
return (firstname, lastname)
|
bdd7aa12a76b6e02fec3cc125d381db9f323df08 | henningBunk/advent-of-code-2020 | /day-3/main.py | 1,129 | 3.71875 | 4 | import re
def read_input_as_list(filename):
return [line for line in open(filename, 'r')]
def read_input(filename):
return open(filename, 'r').read()
def count_trees(input):
return count_trees_w_slope(input, 3, 1)
def count_trees_w_slope(input, right, down):
my_position = 0
trees = 0
for line in input.split('\n')[0::down]:
if line[my_position] == '#':
trees += 1
my_position = (my_position + right) % len(line)
return trees
if __name__ == '__main__':
input = read_input('3.txt')
print(f"Puzzle 1: {count_trees(input)}")
slope_1 = count_trees_w_slope(input, 1, 1)
slope_2 = count_trees_w_slope(input, 3, 1)
slope_3 = count_trees_w_slope(input, 5, 1)
slope_4 = count_trees_w_slope(input, 7, 1)
slope_5 = count_trees_w_slope(input, 1, 2)
print(f"Puzzle 2, Slope 1: {slope_1}")
print(f"Puzzle 2, Slope 2: {slope_2}")
print(f"Puzzle 2, Slope 3: {slope_3}")
print(f"Puzzle 2, Slope 4: {slope_4}")
print(f"Puzzle 2, Slope 5: {slope_5}")
print(f"Multiplied it's {slope_1 * slope_2 * slope_3 * slope_4 * slope_5}")
|
77bf6299b90b63d5c2cacbf4b6a2a7b876a28ba6 | EmaSMach/info2020 | /desafios/complementarios/condicionales/desafio3_menor_de_3.py | 800 | 3.9375 | 4 | # Desafío 3: Determinar si el primero de un conjunto de tres números dados, es menor que los otros dos.
numbers = []
while True:
num = int(input("Ingrese un número: "))
numbers.append(num)
if len(numbers) == 3:
break
print(numbers)
menor = numbers[0] == min(numbers)
if menor:
print("El primer número es el menor")
else:
print("El primer número no es el menor")
# Alternative form
num1 = None
num2 = None
num3 = None
limite = 0
while limite < 3:
num = int(input("Ingrese un número: "))
if limite == 0:
num1 = num
elif limite == 1:
num2 = num
else:
num3 = num
limite += 1
if num1 < num2 and num1 < num3:
print("El primer número es el menor de todos")
else:
print("El primer número no es el menor de todos") |
b4db96e67daa54a64aebcfcaee2a7d90b2d09e11 | Lehcs-py/guppe | /Seção_05/Exercício_03.py | 448 | 4.09375 | 4 | print("""
3. Leia um número real. Se o número for positivo imprima A raiz quadrada. Do contrário, imprima o número ao quadrado.
""")
num = float(input('Insira um número real, positivo = √x, negativo = x².: '))
if num >= 0:
raiz = num ** 0.5
print(f'O número é positivo, portanto, sua raiz quadrada é {raiz}.')
else:
quadrado = num ** 2
print(f'O número é negativo, portanto, o seu quadrado é {quadrado}.')
|
cc8e392108491c68e4366938d0124fdd3c2bff1e | daniel-reich/ubiquitous-fiesta | /YwXwxa6xmoonFRKQJ_22.py | 515 | 3.6875 | 4 |
def josephus(n):
def find_left(n, l):
for i in range(1, len(l)):
j = (n+i)%len(l)
if l[j] == 'a':
return j
if n < 2:
return False
else:
ind = 0
ind_n = -1
arr = ['a' for z in range(n)]
while arr.count('a') > 1:
ind = find_left(ind_n, arr)
ind_n = find_left(ind, arr)
arr[ind_n] = 'x'
return ind
|
30d33c7a2b9b0c7174e792fadd5754d5bc0d2ffb | rachel-ker/MLPipeline | /HW3/etl.py | 7,233 | 3.5 | 4 | '''
ETL - Explore, Transform and Load Code
Rachel Ker
'''
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
###################
# Read Data #
###################
def read_csvfile(csvfile):
'''
Reads in csv and returns a pandas dataframe
Inputs: csv file path
Returns a pandas dataframe
'''
return pd.read_csv(csvfile)
###################
# Explore Data #
###################
# Univariate exploration
def descriptive_stats(df, continuous_var):
'''
Generates simple descriptive statistics e.g. count,
mean, standard deviation, min, max, 25%, 50%, 70%
Inputs:
df: pandas dataframe
var: list of continuous of interest
'''
return df.describe()[continuous_var]
def plot_linegraph(df, continuous_var):
'''
Plot linegraphs
Inputs:
df: pandas dataframe
continuous_var: column name
'''
data = df.groupby(continuous_var).size()
data.plot.line()
plt.show()
def tabulate_counts(df, categorical_var):
'''
Generate counts for categorical variables
Inputs:
df: pandas dataframe
categorical_var: column name
Returns pandas dataframe of counts
'''
count= df.groupby(categorical_var).size()
count= count.to_frame('count')
return count
def plot_barcharts_counts(df, categorical_var):
'''
Plot barcharts by tabulated counts
Inputs:
df: pandas dataframe
categorical_var: column name
'''
data = tabulate_counts(df, categorical_var)
data.plot.bar()
plt.show()
def boxplot(df, var=None):
'''
Creates a box plot
Inputs:
df: pandas dataframe
var: (optional) list of column names
Returns a matplotlib.axes.Axes
'''
if var:
df.boxplot(grid=False, column=var)
else:
df.boxplot(grid=False)
plt.show()
def detect_outliers(df, var, threshold=1.5):
'''
Detecting outliers mathematically using interquartile range
Inputs:
df: pandas dataframe
threshold: (float) indicates the threshold for
defining an outlier e.g. if 1.5, a value outside 1.5
times of the interquartile range is an outlier
Returns a panda series indicating count of outliers
and non-outliers for the variable
'''
q1 = df.quantile(0.25)
q3 = df.quantile(0.75)
iqr = q3 - q1
filtr = (df < (q1 - threshold*iqr)) | (df > (q3 + threshold*iqr))
return filtr.groupby(var).size()
# (Source: https://towardsdatascience.com/ways-to-detect-and-remove-the-outliers-404d16608dba)
def check_missing(df):
'''
Identify the number of missing values for each column
Input:
df: pandas dataframe
Returns a pandas dataframe of the columns and its missing count
'''
return df.isnull().sum().to_frame('missing count').reset_index()
# Bivariate Exploration and Relationships
def scatterplot(df, x, y, y_col):
'''
Creates a scatter plot
Inputs:
df: pandas dataframe
x,y: column names
y_col: (str) column name of target variable
Returns a matplotlib.axes.Axes
'''
df.plot.scatter(x, y, c=y_col, colormap='PiYG')
plt.show()
def plot_corr_heatmap(df):
'''
Plots heatmap of the pairwise correlation coefficient of all features
with respect to the dependent variable
Inputs:
df: pandas dataframe
'''
corr_table = df.corr()
sns.heatmap(corr_table,
xticklabels=corr_table.columns,
yticklabels=corr_table.columns,
cmap=sns.diverging_palette(220, 20, as_cmap=True))
plt.show()
# (Source: https://towardsdatascience.com/a-guide-to-pandas-and-matplotlib-for-data-exploration-56fad95f951c)
def get_corr_coeff(df, var1, var2):
'''
Get a pairwise correlation coefficient of a pair of variables
Inputs:
df: panda dataframe
var1, var2: column names
Returns a float
'''
corr = df.corr()
return corr.loc[var1, var2]
###################
# Preprocessing #
###################
def replace_dates_with_datetime(df, date_cols):
'''
Replace date columns with datetime
Inputs:
df: dataframe
date_cols: list of date columns
Returns dataframe with datetime columns
'''
df[date_cols] = df[date_cols].apply(pd.to_datetime)
return df
def replace_missing_value(df, col, val):
'''
Replace null values with val specified
'''
values = {col: val}
df.fillna(value=values, inplace=True)
return df
def replace_missing_with_mode(data_with_missing, data_to_calculate_mode, cols):
'''
Replaces null values in dataframe with the mode of the col
Inputs:
data_with_missing: pandas df
data_to_calculate_mean: pandas dataframe
cols: list of col
Returns a pandas dataframe with missing values replaced
'''
values = {}
for col in cols:
values[col] = data_to_calculate_mode[col].mode().loc[0]
df = data_with_missing.fillna(value=values)
return df
def replace_missing_with_mean(data_with_missing, data_to_calculate_mean, cols):
'''
Replaces null values in dataframe with the mean of the col
Inputs:
data_with_missing: pandas df
data_to_calculate_mean: pandas dataframe
cols: list of col
Returns a pandas dataframe with missing values replaced
'''
values = {}
for col in cols:
values[col] = data_to_calculate_mean[col].mean()
df = data_with_missing.fillna(value=values)
return df
######################
# Feature Generation #
######################
def discretize(df, continuous_var, lower_bounds):
'''
Discretize continuous variable by creating new var in df
Inputs:
df: pandas dataframe
continuous_var: column name
bounds: list of lowerbound inclusive for discretization
New discretized variable added to dataframe
Returns df
'''
min_val = df[continuous_var].min()
assert lower_bounds[0] == min_val
max_val = df[continuous_var].max()
lower_bounds = lower_bounds + [max_val+1]
replace_dict = {}
for i in range(len(lower_bounds)-1):
key = str(lower_bounds[i]) + "_to_" + str(lower_bounds[i+1])
replace_dict[key] = lower_bounds[i]
df[continuous_var + "_discrete"] = pd.cut(df[continuous_var],
right=False,
bins=list(replace_dict.values()) + [max_val+1],
labels=list(replace_dict.keys()),
include_lowest=True)
return df
def create_dummies(df, categorical_var):
'''
Creates dummy variables from categorical var
and drops the categorical var
Inputs:
df: pandas dataframe
categorical: column name
Returns a new dataframe with dummy variables added
'''
dummy = pd.get_dummies(df[categorical_var],
prefix=categorical_var,
drop_first=True)
df.drop(categorical_var, axis=1, inplace=True)
return df.join(dummy)
|
982400d452e42189567474bd9ab55b5900ebb462 | chetho/python-learning | /hackerrank/Interview Preparation Kit/Warm-up Challenges/1.py | 581 | 3.796875 | 4 | #!/bin/python3
# Sock Merchant
import math
import os
import random
import re
import sys
# Complete the sockMerchant function below.
def sockMerchant(n, ar):
pairs = 0
freq_sock = {}
for item in ar:
if item in freq_sock:
freq_sock[item] += 1
else:
freq_sock[item] = 1
for i in freq_sock:
socks = int(freq_sock[i] / 2)
pairs += socks
return pairs
if __name__ == '__main__':
n = int(input())
ar = list(map(int, input().rstrip().split()))
result = sockMerchant(n, ar)
print(result)
|
9e6045174ae444f36deb9ddf54c388b34bdfb7e9 | bobhall/bobhall_euler | /euler/37/bob.py | 1,456 | 3.625 | 4 | from factors import isPrimeFactors
# I'm just going to put this comment here.
#
# A number n, is right truncatable if n is prime, and it continues to be prime as you "peel" off digits from the right:
# Eg. 31139 -> 3113 -> 311 -> 31 -> 3 (these are all prime, therefore 31139 is a right-truncatable prime)
#
# This function generates a list of truncatable primes of n-digit length and under.
#
def generateRightTruncatables(n):
list1 = [2,3,5,7]
list2 = []
ret_list = []
if n == 1:
return list1
for i in range(1,n):
for l in list1:
for d in [1,3,7,9]:
candidate = 10*l + d
if isPrimeFactors(candidate):
list2.append(candidate)
ret_list.append(candidate)
list1 = list2
list2 = []
return ret_list
def isLeftTruncatable(n):
text = str(n)
for i in range(1,len(text)):
text = text[1:]
if not isPrimeFactors(int(text)):
return False
return True
def func():
nums = set()
i = 2
while len(nums) < 11:
for i in generateRightTruncatables(i):
if isLeftTruncatable(i):
nums.add(i)
i += 1
nums = list(nums)
nums.sort()
print 'The primes that are truncatable from both left and right are: '
for num in nums:
print num
print '\nTheir sum is: ', sum(nums)
func()
|
ca6fec6168b97a6e4082f1a738d6b7f3792a2383 | lukistar/Discworld | /TP/h3/1.py | 1,244 | 4.15625 | 4 | #!/usr/local/bin/python
#school - ТУЕС
#class - 11Б
#num - 20
#name - Красимир Светославов Стойков
#task - Да се съберат номерата от една колонка зажисимост от нещо в някоя друга. От csv файл
def is_int(s):
try:
int(s)
return 1
except ValueError:
return 0
def read_CSV(FILE):
import csv
lines = []
f = open(FILE)
csv_reader = csv.reader( f, delimiter="," )
for row in csv_reader:
lines.append(row)
return lines
# column1 - column with numbers (1 - first column!!!)
# column2 - column with languages
def h(data, column1, column2):
sums = [0, 0, 0]
for row in data[1:]:
st = row[column2-1]
if is_int(row[column1-1]):
if st == "Ruby":
sums[0] = sums[0] + int(row[column1-1])
elif st == "Python":
sums[1] = sums[1] + int(row[column1-1])
elif st == "Perl":
sums[2] = sums[2] + int(row[column1-1])
return sums
choice1 = raw_input("Insert the number of the column with class numbers(1 - first column)")
choice2 = raw_input("Insert the number of the column with used languages(1 - first column)")
sums = h(read_CSV("file3.csv"), int(choice1), int(choice2))
print "Ruby: ", sums[0]
print "Python: ", sums[1]
print "Perl: ", sums[2]
|
222b254915ce6ae53762a13a3dbd9c58cc9846fc | 6306022610113/INEPython | /test3.py | 187 | 3.890625 | 4 | # try block to handle the exception
try:
my_list = []
while True:
my_list.append(int(input()))
# if the input is not-integer, just print the list
except:
print(my_list)
|
7f4f33804bf437fb231e2f7a8f3035ed817b7467 | pranaychandekar/dsa | /src/stacks/stacks.py | 2,013 | 4.375 | 4 | import time
class Stacks:
"""
This class is an implementation of a Stack data structure.
:Authors: pranaychandekar
"""
def __init__(self):
"""
This method initializes a Stack.
"""
self.stack: list = []
def push(self, data):
"""
This method adds a data point to the Stack.
:param data: The data to be stacked.
"""
self.stack.append(data)
def pop(self):
"""
This method removes the first data point in the Stack and returns the same.
:return: The top data point.
"""
top = None
if self.is_empty():
print("Stack is empty!")
else:
top = self.stack.pop()
return top
def top(self):
"""
This method returns the first data point in the Stack.
:return: The first data point.
"""
top = None
if self.is_empty():
print("Stack is empty!")
else:
top = self.stack[-1]
return top
def is_empty(self):
"""
This method checks whether a given Stack is empty and returns a boolean flag accordingly.
:return: The boolean flag indicating the Stack empty status.
"""
return self.size() == 0
def size(self):
"""
This method returns the current size of the Stack.
:return: The size.
"""
return len(self.stack)
if __name__ == "__main__":
tic = time.time()
stack = Stacks()
stack.push(0)
stack.push(1)
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(5)
stack.push(8)
stack.push(13)
stack.push(21)
print("\nThe size of the stack is", stack.size())
print("\nThe top element in the stack:", stack.top())
stack.pop()
while not stack.is_empty():
print("\nThe top element in stack after pop", stack.pop())
toc = time.time()
print("\nTotal time taken", toc - tic, "seconds.")
|
55542edc5a6dd52412fd92926ed3cb1862438c3a | suraj-yathish/Coding-Challenge-Pacman- | /main.py | 1,438 | 3.8125 | 4 | """
This main function invokes pacman with the commands
Input: File with the commands e.g. test_command_1.txt
Output: Pacman object
How to Invoke: python main.py input/test_command_1.txt
"""
import sys
from utils import readFile,preprocessCommands
from pacman import Pacman
from direction import Direction
from grid import Grid
def main():
if len(sys.argv) != 2:
"please pass the file of the commands"
exit(0)
Commands = readFile(sys.argv[1])
orientations = ["NORTH", "EAST", "SOUTH", "WEST"]
grid = Grid()
pacman = Pacman(orientations=orientations)
if "PLACE" not in Commands[0]:
print("The first valid command to the pacman is a PLACE command, please specify it")
elif "PLACE" in Commands[0]:
for command in Commands:
if "PLACE" in command:
command_splitted = preprocessCommands(command)
x_axis = float(command_splitted[0])
y_axis = float(command_splitted[1])
facing = command_splitted[2]
orientations_index = orientations.index(facing)
pacman_position = Direction(x_axis=x_axis, y_axis=y_axis)
pacman = pacman.place(Direction=pacman_position,grid=grid,facing=orientations_index/2.0)
else:
pacman = getattr(pacman,command.lower())()
if __name__ == "__main__":
main() |
c865916c9cb416826a7793b45a8d583137c09294 | MrHamdulay/csc3-capstone | /examples/data/Assignment_9/ntnlus001/question3.py | 545 | 3.671875 | 4 | def check(ls):
for j in range (9):
for n in range(9):
if ls[j].count(ls[j][n]) > 1:
print("Sudoku grid is not valid")
cols = [[row[i] for row in ls] for i in range(9)]
for i in range(0,9):
for j in range(0,9):
if cols[i].count(cols[i][j]) > 1:
print("Sudoku grid is not valid")
angel = []
for t in range(3):
ang = ls[t]
for u in range(3):
angel.append(ang[u])
for be in range(9):
if angel.count(angel[be]) > 1:
print("Sudoku grid is not valid")
print("Sudoku grid is valid")
|
e61754e2c02b0df80bff1065f73d6bcbb317c0ee | chenhuang/leetcode | /connect.py | 3,153 | 4.34375 | 4 | '''
Populating Next Right Pointers in Each Node
Given a binary tree
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Note:
You may only use constant extra space.
You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example,
Given the following perfect binary tree,
1
/ \
2 3
/ \ / \
4 5 6 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ / \
4->5->6->7 -> NULL
https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node/
'''
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
# @param root, a tree node
# @return nothing
# Obs: looks like a BFS
def connect(self, root):
queue = [(root,1)]
while len(queue) > 0:
(node,lvl) = queue.pop(0)
if node != None:
if node.left:
queue.append((node.left,lvl+1))
if node.right:
queue.append((node.right,lvl+1))
if len(queue) > 0 and lvl == queue[0][1]:
node.next = queue[0][0]
def connect_II(self, root):
if not root:
return
# Child's right
p = root.next
while p != None:
if p.left:
p = p.left
break
elif p.right:
p = p.right
break
else:
p = p.next
if root.left and root.right:
root.left.next = root.right
elif root.right:
root.right.next = p
elif root.left:
root.left.next = p
self.connect_II(root.left)
self.connect_II(root.right)
def connect_1(self, root):
head = None # head of the next level
prev = None # leading node on the next level
cur = root # current node of current level
while cur is not None:
while cur is not None: # Iteration the current level
if cur.left is not None: # Left child
if prev is not None:
prev.next = cur.left
else:
head = cur.left
prev = cur.left
if cur.right is not None:
if prev is not None:
prev.next = cur.right
else:
head = cur.right
prev = cur.right
cur = cur.next # Move to next node
# Move to next level
cur = head
head = None
prev = None
|
6d736af009e0715520192f50de3159adcd6291b8 | anebz/ctci | /01. Arrays and strings/1.5. levenshtein.py | 1,682 | 3.640625 | 4 | import unittest
def levenshtein(s1, s2):
if abs(len(s1) - len(s2)) > 1:
return False
if s1 == s2:
return True
len1 = len(s1)
len2 = len(s2)
flag = False
if len1 == len2: # equal lengths
for i in range(len1):
if s1[i] != s2[i]:
if flag:
return False
flag = True
return True
elif len1 < len2: # s1 shorter than s2
for i in range(len1):
if not flag:
if s1[i] != s2[i]:
if flag:
return False
flag = True
else: # there's already one difference
if s1[i] != s2[i + 1]:
return False
return True
elif len2 < len1: # s2 shorter than s1
for i in range(len2):
if not flag:
if s1[i] != s2[i]:
if flag:
return False
flag = True
else: # there's already one difference
if s1[i + 1] != s2[i]:
return False
return True
class Test(unittest.TestCase):
dataT = [("", ""), ("an", "a"), ("a", "an"), ("ane", "ae"),
("ane", "ne"), ("asdfgh", "asdgh"), ("asdf", "asgf")]
dataF = [("asdfg", "adfgh"), ("an", "ne"), ("asdf", "as")]
def test_unique(self):
for test in self.dataT:
res = levenshtein(*test)
self.assertTrue(res)
for test in self.dataF:
res = levenshtein(*test)
self.assertFalse(res)
return
if __name__ == "__main__":
unittest.main()
|
246f8eb1b14863b7061c419dc7a4362ab2e45b3e | oden6680/AtCoder | /other/tenpuro2012_A/tempCodeRunnerFile.py | 113 | 3.65625 | 4 | S = input()
S = list(S.split(' '))
res = []
for i in S:
if i != ' ':
res.append(i)
print(S.join(',')) |
ed9d5c1beced88de51c45128eeeab707fde692dd | PavanKReddi/NetworkAutomationUsingPython | /open_excel_file.py | 859 | 3.640625 | 4 | # open_excel_file.py
import xlrd
def open_excel_file(workbook_name):
workbook = xlrd.open_workbook(workbook_name)
worksheet = workbook.sheet_by_name('Sheet1')
return worksheet
def main():
'''
Open "switch_list.xlsx" and display its data
'''
worksheet = open_excel_file("switch_list.xlsx")
num_rows = worksheet.nrows - 1
num_cells = worksheet.ncols - 1
curr_row = -1
while curr_row < num_rows:
curr_row += 1
row = worksheet.row(curr_row)
print 'Row:', curr_row
curr_cell = -1
while curr_cell < num_cells:
curr_cell += 1
# Cell Types: 0=Empty, 1=Text, 2=Number, 3=Date, 4=Boolean, 5=Error, 6=Blank
cell_type = worksheet.cell_type(curr_row, curr_cell)
cell_value = worksheet.cell_value(curr_row, curr_cell)
print '\t', cell_type, ':', cell_value
if __name__ == "__main__":
main() |
cee407494f07f0176e7217fda18d4ce3a74ca883 | conorfalvey/Coding-Samples | /Karan-Example-Project-Solutions/Python/Numerical/ChangeReturn.py | 828 | 3.859375 | 4 | import math
def change(n):
total = str(math.floor(n * 100)/100)
n = int(n * 100)
quarters = 0
dimes = 0
nickels = 0
pennies = 0
while (n >= 5):
if (n - 25 >= 0):
quarters = quarters + 1
n = n - 25
elif (n - 10 >= 0):
dimes = dimes + 1
n = n - 10
elif (n - 5 >= 0):
nickels = nickels + 1
n = n - 5
pennies = n
print(str(quarters), "Quarters,", str(dimes), "Dimes,",
str(nickels), "Nickels,", str(pennies), "Pennies. Total:", total)
cost = float(input("What is the cost of the item: "))
given = float(input("What is the amount paid with: "))
if (cost > given):
print("Not enough money given!")
elif (cost == given):
print("Exact change given!")
else:
change(given - cost)
|
6f0dcfb67ccf54b624f8b418f4bdff244ebb17cd | lixinchn/LeetCode | /src/0108_ConvertSortedArrayToBinarySearchTree.py | 1,444 | 3.859375 | 4 | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
@staticmethod
def create(arr):
head = None
this = None
left, right = False, False
prev_nodes = []
for val in arr:
node = TreeNode(val)
if not head:
head = node
this = node
continue
if left and right:
this = prev_nodes.pop(0)
left = False
right = False
if not left:
this.left = node
left = True
elif not right:
this.right = node
right = True
if node and node.val:
prev_nodes.append(node)
return head
class Solution(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
return self.do(nums, 0, len(nums) - 1)
def do(self, nums, begin, end):
if begin > end:
return None
middle = (begin + end) / 2
num = nums[middle]
node = TreeNode(num)
node.left = self.do(nums, begin, middle - 1)
node.right = self.do(nums, middle + 1, end)
return node
if __name__ == "__main__":
solution = Solution()
head = solution.sortedArrayToBST([1,2,3,4,5,6,7,8])
print head |
4b2d3b19cdb41a9fb095c6ee6476a3cb13250126 | unlimitediw/LCContest | /Contest_102.py | 5,934 | 3.515625 | 4 | import math
class Solution:
def sortArrayByParity(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
even = []
odd = []
for digit in A:
if digit % 2 == 0:
even.append(digit)
else:
odd.append(digit)
return even + odd
def totalFruit(self, tree):
"""
:type tree: List[int]
:rtype: int
"""
memo = []
cur_1 = tree[0]
cur_2 = None
group_start = 0
continuous_start = 0
start = 0
treeLength = len(tree)
for i in range(treeLength):
if tree[i] != cur_1:
start = i
continuous_start = i
cur_2 = tree[i]
break
if i == treeLength - 1:
return treeLength
for i in range(start, treeLength):
if tree[i] != cur_2 and tree[i] != cur_1:
memo.append(i - group_start)
cur_1 = tree[continuous_start]
cur_2 = tree[i]
group_start = continuous_start
continuous_start = i
elif tree[i] != tree[continuous_start]:
continuous_start = i
if i == treeLength - 1:
memo.append(i + 1 - group_start)
return max(memo)
def sumSubarrayMinsPre(self, A):
"""
:type A: List[int]
:rtype: int
"""
n = len(A)
total = sum(A)
min_memo = []
pre = float('inf')
for i in range(n - 1, -1, -1):
pre = min(pre, A[i])
min_memo.append(pre)
min_memo = min_memo[::-1]
for i in range(n):
remain = n - i - 1
cur = A[i]
for j in range(1, remain + 1):
if cur < min_memo[i + j]:
total += (remain - j + 1) * cur
break
if A[i + j] < cur:
cur = A[i + j]
total += cur
return total % (10 ** 9 + 7)
# use dp to solve the problem with left min and right min
# solve the left min and right min problem with stack
def sumSubarrayMins(self, A):
n = len(A)
memo = []
total = 0
# solve left min and right min
for i in range(n):
j = i
while memo and A[i] < memo[-1][0]:
cur = memo[-1]
total += cur[0] * (i - cur[1]) * (cur[1] - cur[2] + 1)
j = cur[2]
memo.pop()
memo.append([A[i], i, j])
while memo:
cur = memo[-1]
total += cur[0] * (n - cur[1]) * (cur[1] - cur[2] + 1)
memo.pop()
return total % (10 ** 9 + 7)
def superpalindromesInRange(self, L, R):
"""
:type L: str
:type R: str
:rtype: int
"""
count = 0
l, r = int(L), int(R)
ac_l, ac_r = int(math.ceil(l ** 0.5)), int(r ** 0.5)
a = [1,4,
9,
121,
484,
10201,
12321,
14641,
40804,
44944,
1002001,
1234321,
4008004,
100020001,
102030201,
104060401,
121242121,
123454321,
125686521,
400080004,
404090404,
10000200001,
10221412201,
12102420121,
12345654321,
40000800004,
1000002000001,
1002003002001,
1004006004001,
1020304030201,
1022325232201,
1024348434201,
1210024200121,
1212225222121,
1214428244121,
1232346432321,
1234567654321,
4000008000004,
4004009004004,
100000020000001,
100220141022001,
102012040210201,
102234363432201,
121000242000121,
121242363242121,
123212464212321,
123456787654321,
400000080000004,
10000000200000001,
10002000300020001,
10004000600040001,
10020210401202001,
10022212521222001,
10024214841242001,
10201020402010201,
10203040504030201,
10205060806050201,
10221432623412201,
10223454745432201,
12100002420000121,
12102202520220121,
12104402820440121,
12122232623222121,
12124434743442121,
12321024642012321,
12323244744232321,
12343456865434321,
12345678987654321,
40000000800000004,
40004000900040004]
start = -1
end = -1
for i in range(len(a)):
print(a[i])
if start == -1:
if l <= a[i]:
start = i
else:
if r < a[i]:
end = i - 1
break
if i == len(a) - 1 and end == -1:
end = len(a) - 1
return end - start + 1
def superpalindromesInRangeBru(self, L, R):
"""
:type L: str
:type R: str
:rtype: int
"""
count = 0
l, r = int(L), int(R)
ac_l, ac_r = int(math.ceil(l ** 0.5)), int(r ** 0.5)
for i in range(ac_l, ac_r + 1):
check = str(i)
if check == check[::-1]:
check2 = str(i ** 2)
if check2 == check2[::-1]:
count += 1
print(check2)
return count
print(Solution().superpalindromesInRange("38455498359",
"999999999999999999")) |
3f0addba2e7310cf1bfff519ec0a6041a4b83fa4 | FWNT/ycsh_python_course | /L07/ttt_check_wins.py | 1,901 | 3.65625 | 4 | # 撰寫一程式,檔案名稱 ttt_check_wins.py
# 定義棋盤格狀態變數 cell_1 ~ cell_9 與目前的棋子變數 chess 如下,
# 檢查該棋子是否已經在該盤面上取得勝利條件,
# (任意直線上的三個格子的棋子皆和目前的棋子相同),
# 如果已經取得勝利條件,顯示 '{棋子} 勝利,結束程式',並退出程式
# (請替換其值)
# 棋盤格變數:保存棋盤狀態的變數
# 變數編號對應的棋盤位置如下
# 1 | 2 | 3
# ---+---+---
# 4 | 5 | 6
# ---+---+---
# 7 | 8 | 9
cell_1 = ' '
cell_2 = ' '
cell_3 = 'o'
cell_4 = 'x'
cell_5 = 'o'
cell_6 = 'o'
cell_7 = 'x'
cell_8 = ' '
cell_9 = 'x'
# 目前棋子變數:保存目前使用的棋子
chess = 'x'
# 使用者指定棋子位置
# TODO: 程式寫這裡
position=int(input())
if position == 1 and cell_1 !=' ':
print('錯誤')
exit()
elif position ==2 and cell_2 !=' ':
print('錯誤')
exit()
elif position ==3 and cell_3 !=' ':
print('錯誤')
exit()
elif position ==4 and cell_4 !=' ':
print('錯誤')
exit()
elif position ==5 and cell_5 !=' ':
print('錯誤')
exit()
elif position ==6 and cell_6 !=' ':
print('錯誤')
exit()
elif position ==7 and cell_7 !=' ':
print('錯誤')
exit()
elif position ==8 and cell_8 !=' ':
print('錯誤')
exit()
elif position ==9 and cell_9 !=' ':
print('錯誤')
exit()
# 根據指定位置,更新對應的棋盤格狀態變數 cell_1 ~ cell_9,
# TODO: 程式寫這裡
if position == 1:
cell_1=chess
elif position ==2:
cell_2=chess
elif position ==3:
cell_3=chess
elif position ==4:
cell_4=chess
elif position ==5:
cell_5=chess
elif position ==6:
cell_6=chess
elif position ==7:
cell_7=chess
elif position ==8:
cell_8=chess
elif position ==9:
cell_9=chess
# 判斷是否勝利並顯示結果
# TODO: 程式寫這裡
if position==1 or position==8:
print('勝利') |
a723bb6e8db3faf3625f6432ed28b0fed6b5dcba | dabanin/GeekBrains_Python | /hw01_hard.py | 1,673 | 3.5 | 4 | __author__ = 'Абанин Дмитрий Сергеевич'
# Задание-1:
# Ваня набрал несколько операций в интерпретаторе и получал результаты:
# Код: a == a**2
# Результат: True
# Код: a == a*2
# Результат: True
# Код: a > 999999
# Результат: True
# Вопрос: Чему была равна переменная a,
# если точно известно, что её значение не изменялось?
# Подсказка: это значение точно есть ;)
#Математика подсказывает, что единственное подходчщее число - бесконечность.
#Гугл подсказывает, что в Python бесконечность выражается float('inf')
a = float('inf')
=======
__author__ = 'Абанин Дмитрий Сергеевич'
# Задание-1:
# Ваня набрал несколько операций в интерпретаторе и получал результаты:
# Код: a == a**2
# Результат: True
# Код: a == a*2
# Результат: True
# Код: a > 999999
# Результат: True
# Вопрос: Чему была равна переменная a,
# если точно известно, что её значение не изменялось?
# Подсказка: это значение точно есть ;)
#Математика подсказывает, что единственное подходчщее число - бесконечность.
#Гугл подсказывает, что в Python бесконечность выражается float('inf')
a = float('inf')
|
b236f7feca0b1a1408e578b4878eff1435c2d4b4 | zhaozhenyu/push | /python复习/p4/problem4.py | 526 | 3.53125 | 4 | import numpy as np
def unnest(alist):
k=[] ### append alist to k and k is str type
flat_list=[]##
for i in alist:
k += str(i)
for i in k:
if str.isnumeric(i):
flat_list.append(int(i))
return flat_list
#
# a=[[2,2,2],[3,3,3],[4,4,4]]
# print(unnest(a))
# z=[]
# print(type(a[0]))
# # for i in a :
# k+=str(i)
# for i in k:
# if str.isnumeric(i):
# z.append(int(i))
# print(z)
# print(c)
# flat_list = [item for sublist in l for item in sublist]
# print (flat_list) |
01c167f122dad687b2337c36184075ad561b8ec7 | paulosergio-dev/exerciciopython | /questao14.py | 1,001 | 3.921875 | 4 | '''
Elabore um programa que leia o salário de um empregado e com base na tabela abaixo calcule
e informe sua gratificação e seu salário líquido.
'''
salario = float(input("Informe o salário: "))
if salario < 2000:
aumento = 5
resultado = salario + (salario * aumento/100)
print("Sua gratificação é de 5%")
print("Seu salário líquido é de: {}".format(resultado))
elif salario > 2000 and salario < 2500:
aumento = 10
resultado = salario + (salario * aumento/100)
print("Sua gratificação é de 10%")
print("Seu salário líquido é de: {}".format(resultado))
elif salario > 2500 and salario < 3000:
aumento = 15
resultado = salario + (salario * aumento/100)
print("Sua gratificação é de 15%")
print("Seu salário líquido é de: {}".format(resultado))
else:
aumento = 20
resultado = salario + (salario * aumento/100)
print("Sua gratificação é de 20%")
print("Seu salário líquido é de: {}".format(resultado)) |
d6e80f3b183efa3cb03b926f893c37d11ec88f03 | USTH-Coders-Club/API-training | /caller.py | 393 | 3.84375 | 4 | #import the library to make http request
import requests
#URL of the API
URL = "http://127.0.0.1:5000"
dating_id = input("Id of the guy you want to flirt")
param ={
'id':dating_id,
}
#Make an API request and store date to r
r = requests.get(url= URL, params=param)
#Json data
data = r.json()
#extract count from data
n = data['age']
name = data['name']
print(f"age of {name} is {n}") |
6c7d8f09d8987fc9836b67f4a2c86b769676c850 | wmsj100/CodeSpace | /python/project/mao_pou_xun_huan.py | 833 | 4.15625 | 4 | """
先不想着用递归调用,
先实现思路
走一次循环,再循环中比较相邻俩个值的大小
"""
import sys
def sort_max_list(list):
for index, num in enumerate(list):
if index == len(list) - 1:
break
else:
if num > list[index+1]:
list[index], list[index + 1] = list[index+1], num
print(list)
def sort_list(list):
result = []
for index in range(len(list) - 1):
sort_max_list(list)
def mao_pao(list):
for i in range(len(list) -1):
for j in range(len(list) - i - 1):
if list[j] > list[j+1]:
list[j], list[j+1] = list[j+1], list[j]
print(list)
def init():
temp = [23,9,56,33,1,3,345,12,0]
sort_list(temp)
# mao_pao(temp)
if __name__ == '__main__' :
init()
|
ebf795126773c6ea82c8aaab05b248a4c0fb7995 | bufordsharkley/advent_of_code | /2016/day19.py | 1,199 | 3.546875 | 4 | num = 5
def last_elf(num):
elfs = [x + 1 for x in range(num)]
position = 1
while len(elfs) > 1:
if position == 0:
position = len(elfs) % 2
elfs = [x for ii, x in enumerate(elfs) if ii % 2]
else:
position = (1 + len(elfs)) % 2
elfs = [x for ii, x in enumerate(elfs) if not ii % 2]
return elfs[0]
def last_middle_old(num):
elfs = [x + 1 for x in range(num)]
while len(elfs) > 1:
print elfs[len(elfs) // 2]
del elfs[len(elfs) // 2]
elfs.append(elfs.pop(0))
def moves(elfs):
lenn = len(elfs)
count = lenn
ii = lenn // 2
jump = 1 if lenn % 2 else 0
while count > 1:
if elfs[ii] is not None:
print elfs[ii]
elfs[ii] = None
ii += jump
jump = 0 if jump == 1 else 1
count -= 1
ii += 1
if ii > (lenn - 1):
ii = ii % lenn
yield ii
def last_middle(num):
elfs = {x: x + 1 for x in range(num)}
for move in moves(elfs):
pass
print [x for x in elfs.values() if x is not None][0]
def main():
assert last_elf(5) == 3
num = 3001330
num = 12
last_middle_old(num)
print
last_middle(num)
return
last_middle(12)
last_middle(num)
if __name__ == "__main__":
main()
|
9ced2b736545ce4b6b3c2eac7c68aa833754ae43 | RishabhK88/PythonPrograms | /5. DataStructures/SortingLists.py | 708 | 4.6875 | 5 | numbers = [3, 51, 2, 8, 6]
# List is sorted in ascending order
numbers.sort()
print(numbers)
# List is sorted in descending order
numbers.sort(reverse=True)
print(numbers)
# Below is used to sort the list and print but not change the original list
print(sorted(numbers))
print(sorted(numbers, reverse=True))
# To sort something like a bunch of tuples such as in items below, we have to define
# a function
items = [
("Product1", 10),
("Product2", 9),
("Product3", 12)
]
def sort_item(item):
return item[1]
items.sort(key=sort_item)
print(items)
# The above code of the function is very time consuming and so the above can also be
# done using lambda function
|
a05174f2d4cd3540cfd28c181d5d8fae37cc4d2a | jetboom1/python_projects | /files/romeo and julietta.py | 649 | 3.859375 | 4 | '''Возникли проблемы с получением доступа к файлу через интернет, поэтому пришлось скачать его локально'''
from operator import itemgetter
with open('intro.txt') as romeo:
counts = dict()
for i in romeo.readlines():
words = i.lower().split()
for k in words:
if k in counts:
counts[k]+=1
else:
counts[k]=1
counts = sorted(counts.items(), key=itemgetter(1), reverse=True)
for k in range(len(counts)):
for i in range(len(counts[k])):
print(counts[k][i], end=' ')
print() |
42f9e087749c4f300554a07f330e83b284ac9879 | sassyst/leetcode-python | /leetcode/contest/N-RepeatedElementinSize2NArray.py | 342 | 3.625 | 4 | def repeatedNTimes(A):
"""
:type A: List[int]
:rtype: int
"""
A.sort()
i, j = 0, 1
while j < len(A):
if A[i] == A[j]:
return A[i]
else:
i += 1
j += 1
s = [1, 2, 3, 3]
ret = repeatedNTimes(s)
print(ret)
s = [2, 1, 2, 5, 3, 2]
ret = repeatedNTimes(s)
print(ret)
|
0e168013704c64fd99b323d89584df1074be6506 | zois-tasoulas/DailyInterviewPro | /p21/p21.py | 913 | 3.703125 | 4 | def minimalSubarray(lst, s):
leftIndex = 0
arrayLength = len(lst)
minSubarray = arrayLength + 1
currentSum = 0
for rightIndex, element in enumerate(lst):
currentSum += element
if currentSum > s:
while currentSum > s and leftIndex <= rightIndex:
currentSum -= lst[leftIndex]
leftIndex += 1
if currentSum == s and rightIndex - leftIndex + 1 < minSubarray:
minSubarray = rightIndex - leftIndex + 1
if minSubarray == 1: #A subarray of one element is the shortest possible subarray
break
return minSubarray if minSubarray <= arrayLength else 0
if __name__ == '__main__':
array = [2, 3, 1, 3, 4, 9, 5, 4, 3, 2, 7, 6, 1, 3, 15, 4, 4, 1, 4, 42, 5]
s = 9
print(minimalSubarray(array, s))
s = 44
print(minimalSubarray(array, s))
s = 39
print(minimalSubarray(array, s))
|
d8c7507f42fcb479ef7ebf8560cb5343348f7178 | kjnh10/pcw | /work/atcoder/abc/abc019/B/answers/232803_nanae.py | 324 | 3.671875 | 4 | import sys
def solve():
s = input() + '#'
ans = s[0]
pch = s[0]
cnt = 1
for ch in s[1:]:
if ch != pch:
ans += str(cnt) + ch
cnt = 1
pch = ch
else:
cnt += 1
ans = ans.rstrip('#')
print(ans)
if __name__ == '__main__':
solve() |
b92dbe12c992ea13d2e1409e2800712c2577ebb4 | A01378649/Snake | /snake.py | 3,732 | 4.21875 | 4 | """
This program contains functions to run the game of snake.
Welcome to snake!
You move with the arrows.
Avoid crashing with the walls or your own body.
Eat the food to grow.
Good luck!
"""
# Related third party libraries.
from turtle import update, ontimer, setup, \
hideturtle, tracer, listen, \
onkey, done, clear, color
from random import randrange, getrandbits
from freegames import square, vector
# Global variables.
food = vector(0, 0)
snake = [vector(10, 0)] # List of vectors.
aim = vector(0, -10)
# Set of colors.
five_colors = {"green", "blue", "orange", "turquoise", "yellow"}
# Timer controller for food movement
cont = 0
print(__doc__) # Usage information for the user.
def change(x, y):
"""Set the x and y values of aim vector to x and y parameters"""
aim.x = x
aim.y = y
def inside(head):
"""Returns whether or not head vector fits in screen limits"""
return -200 < head.x < 190 and -200 < head.y < 190
def move():
"""
Moves the snake in the direction that the aim vector specifies.
This function takes a copy of the last element from snake list.
It moves this copy in the direction specified by the global
variable aim. It checks if the copy ends up out of bounds or
inside the snake´s body. It adds this head to the snake list.
It checks if the snake has eaten the food, and if it hasn´t,
it removes the added head, if it has, it respawns the food.
Finally it draws the snake and the food and waits 100 ms to
be called again.
Parameters:
None
Returns:
None
"""
head = snake[-1].copy() # Copy of the last vector in snake.
head.move(aim) # Modify copied vector with direction of aim.
# Losing conditions.
if not inside(head) or head in snake:
square(head.x, head.y, 9, "red")
update()
return
snake.append(head) # Add a position to the list.
# Snake eating the food.
if head == food:
print("Snake:", len(snake))
food.x = randrange(-15, 15) * 10
food.y = randrange(-15, 15) * 10
else:
snake.pop(0) # Remove the added position, no food eaten.
clear()
# Draw the snake.
global snake_color
for body in snake:
square(body.x, body.y, 9, snake_color)
#Move the food 1 time each time the snake moves 5 times
global cont
cont = (cont + 1) % 5
if(cont == 0):
movef()
# Draw the food.
global food_color
square(food.x, food.y, 9, food_color)
update() # Update the screen when tracer is off.
ontimer(move, 100) # Wait 100 ms to call move.
def movef():
"""
This function moves the snake food to random contiguous position.
This function takes no arguments.
"""
hztl = bool(getrandbits(1))
if(inside(food)):
food.move(vector(randrange(-1,2) * 10 * int(hztl),
randrange(-1,2) * 10 * int(not hztl)))
else:
food.x = 0
food.y = 0
# Initial steps.
setup(420, 420, 370, 0)
hideturtle() # Turtle invisible.
tracer(False) # Turns off the turtle animation.
# Collect key events.
listen()
# Functions to be run after certain keys are pressed.
onkey(lambda: change(10, 0), "Right")
onkey(lambda: change(-10, 0), "Left")
onkey(lambda: change(0, 10), "Up")
onkey(lambda: change(0, -10), "Down")
# Get 2 distinct colors from color set.
food_color = next(iter(five_colors))
five_colors.remove(food_color)
snake_color = next(iter(five_colors))
move()
done() # The event loop. |
ed0780241767285486b4ed1e3c8e7f0510afc5ba | Amaayezing/ECS-10 | /FractionAddRadhav/frac_add.py | 1,922 | 4.03125 | 4 | #Raghav Dogra & Maayez Imam 11/13/17
#Fraction Add program
def is_int(num):
if len(num) == 0:
return False
elif num.strip().isdigit():
return True
elif num.strip()[0] == '-' and num.strip()[1:].isdigit():
return True
else:
return False
def gcd(a, b):
if a < b:
a, b = b, a
while True:
r = a % b
if r == 0:
return b
a, b = b, r
def frac_add():
num1 = "a"
denom1 = "a"
while not is_int(num1) or not is_int(denom1) or int(denom1) <= 0:
str = input("Enter a fraction: ").strip()
if str.count("/") == 1:
str = str.split("/")
num1, denom1 = str
elif is_int(str):
num1 = str
denom1 = "1"
num1 = int(num1)
denom1 = int(denom1)
num2 = "a"
denom2 = "a"
while not is_int(num2) or not is_int(denom2) or int(denom2) <= 0:
str = input("Enter another fraction: ").strip()
if str.count("/") == 1:
str = str.split("/")
num2, denom2 = str
elif is_int(str):
num2 = str
denom2 = "1"
num2 = int(num2)
denom2 = int(denom2)
save_num1 = num1
save_denom1 = denom1
save_num2 = num2
save_denom2 = denom2
if gcd(denom1, denom2)== 1:
num1 *= denom2
num2 *= denom1
denom1 = denom1 * denom2
denom2 = denom1
else:
temp1 = denom1/gcd(denom1, denom2)
temp2 = denom2/gcd(denom1, denom2)
num1 *= temp2
num2 *= temp1
denom1 *= temp2
denom2 *= temp1
num_final = num1 + num2
denom_final = denom1
temp = gcd(num_final, denom_final)
if (temp != 1):
num_final /= abs(temp)
denom_final /= abs(temp)
print("%s/%s + %s/%s = %s/%s" % (int(save_num1),int(save_denom1),int(save_num2),int(save_denom2),int(num_final),int(denom_final)))
frac_add() |
7d4e5f0fb0460d3b9bb11a5f24c037aa5a0073e5 | JorgeTowersmx/python2020 | /sentencias.py | 163 | 4 | 4 | name = "Diego1" #Asignacion de valor a una variable
if name == "Diego":
print("Aupa Diego")
else:
print("¿Quien eres?")
print("¡No eres Diego!") |
ed56bca392cab999198a8b22dd33eb00cf00439e | bzelditch/EPI | /Ch8/test.py | 371 | 3.5625 | 4 | from search import DFS, BFS
from queueG import Queue
from graph import Node
root = Node(1)
b = Node(3)
c = Node(4)
d = Node(10)
e = Node(11)
root.addNeighbor(b) # There's a better way
b.addNeighbor(root)
b.addNeighbor(e)
e.addNeighbor(b)
root.addNeighbor(c)
c.addNeighbor(root)
c.addNeighbor(d)
d.addNeighbor(c)
#print("DFS: ")
#DFS(root)
print("BFS: ")
BFS(root) |
a1d3a80c9775890ab0b71a9b74972c03a1739e4a | AdamZhouSE/pythonHomework | /Code/CodeRecords/2526/58547/261475.py | 191 | 3.875 | 4 | def func():
arr0 = [int(x) for x in input()[1:-1].split(",") if x.isdigit()]
arr1 = [int(x) for x in input()[1:-1].split(",") if x.isdigit()]
print(sorted(arr0 + arr1))
func()
|
6a7d2a8d06995e9b6113b98e545ac5f48b46b53f | wyh19/PythonCrashCourse | /8-函数/1-定义函数.py | 3,508 | 4.1875 | 4 | # 函数就是带名字的代码块,用于完成具体的工作;如果一段代码会多次被执行,那么应该考虑将其定义为函数,然后调用函数执行该段代码
# 函数定义的形式为
# def 函数名():
# """函数说明(可选)"""
# 函数体(缩进)
def greet_user():
"""显示简单的问候语"""
print('Hello')
# 函数调用
greet_user()
# 通过参数,想函数传递额外数据,使其具备更多功能
def greet_user2(username):
"""显示姓名的问候语"""
print("Hello, " + username.title() + "!")
# 函数调用,传入参数'jesse',该参数赋值给函数形参username
# 根据学术划分,username是形参(函数定义时的参数),'jesse'是实参(实际传入的参数);函数调用时,实参赋值给形参
greet_user2('jesse')
# 当有函数有多个参数时,实参可以按形参的顺序依次传入,成为位置实参
def describe_pet(animal_type, pet_name):
"""显示宠物的信息"""
print("I have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
# 两个参数依次传入,分别对应各自所在位置的形参
print('\n---按顺序传参---')
describe_pet('hamster', 'harry')
# 思考:如果参数很多,顺序容易考错,如果我可以指定参数名传参就好了,这可以吗?
# 答案: 可以的,python支持关键字实参,即给指定名称的形参传入参数,看下面示例
# 给指定参数名传参,再也不用担心顺序问题了
print('\n---关键字传参---')
describe_pet(pet_name='harry', animal_type='hamster')
# 参数默认值,即在定义函数时,给某些参数指定默认值,在调用函数时,当不给这些含有默认值的参数传参时,它们使用各自的默认值作为参数
def describe_pet2(pet_name, animal_type='dog'):
"""显示宠物的信息"""
print("I have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
# 可以灵活的混合使用默认参数、关键字传参
print('\n---使用默认值---')
describe_pet2('旺财')
describe_pet2(pet_name='旺财')
print('\n---覆盖默认值---')
describe_pet2('喵喵', 'cat')
describe_pet2('喵喵', animal_type='cat')
# 将实参变成可选,即将有默认值得参数放置在参数列表末尾
def print_name(first_name, last_name, middle_name=''):
"""按正常顺序,middle_name应该放在第二个,但是因为有些人没有middle_name,那么将其放在最后,并设置默认值为空"""
if middle_name:
full_name = first_name+' '+middle_name+' '+last_name
else:
full_name = first_name + ' ' + last_name
print(full_name)
print('\n---实参可选---')
print_name('Jim','Green')
print_name('Anne','Hathaway','Jacqueline')
# 函数返回值:函数运算完毕,使用return返回的值
def get_formatted_name(first_name, last_name):
"""返回整洁的姓名"""
full_name = first_name + ' ' + last_name
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print('\n---函数返回值---')
print(musician)
# 函数返回值可以是任何数据类型,比如字典
def build_person(first_name, last_name):
"""返回一个字典,其中包含有关一个人的信息"""
person = {'first': first_name, 'last': last_name}
return person
musician = build_person('jimi', 'hendrix')
print('\n---函数返回值-字典---')
print(musician)
|
dccb8b00f8a465622970e9c76232a0483faeb1d0 | lraulin/algorithms | /js/sort/bubble_sort.py | 415 | 4 | 4 | # Don't ever use! This is the worst sorting algorithm!
# O(n^2)
def bubble_sort(arr):
swapped = True
while swapped:
swapped = False
for i in range(len(arr)-1):
if arr[i] > arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
swapped = True
print(arr)
return arr
arr = [22, 17, 5, 9, 20, 21, 7, 11, 14, 16, 8, 13, 12, 19]
bubble_sort(arr)
|
4b1d353ce66f7289ef71cdc6169af352687fcf8f | shin-kanouchi/NLP100knock | /test064.py | 769 | 3.5625 | 4 | #!/usr/bin/python
#-*-coding:utf-8-*-
#2014/06/17 17:12:21 Shin Kanouchi
"""(64) 63の結果を用い,TF*IDF値が高い名詞句トップ100のリストを作成せよ.このとき,数字を含む表現はトップ100のリストから除外せよ."""
def sort_tf_idf():
import re
dict = {}
for line in open("63_output_tf_idf.txt"):
word,tf_idf,tf,df = line.strip().split("\t")
r = re.compile(r"[0-9]")
if not r.search(word):
dict[word] = float(tf_idf)
return dict
def print_tf_idf(dict):
j=0
for word,i in sorted(dict.items(),key=lambda x:x[1],reverse = True):
if j>=100:
break
print word ,i
j+=1
if __name__ == '__main__':
dict= sort_tf_idf()
print_tf_idf(dict)
#shin:test kanouchishin$ python test64.py > 64_output_tf_idf_top_100.txt
|
98b2a446f91d3b0045878ce4eb0cfdae2219225c | jisshub/python-django-training | /unittesting/test2.py | 1,333 | 3.734375 | 4 | import unittest
import calc
class TestCalc(unittest.TestCase):
def test_add(self):
self.assertEqual(calc.add(10, 20), 30)
self.assertEqual(calc.add(-1, -1), -2)
self.assertEqual(calc.add(-1, 1), 0)
def test_multiply(self):
self.assertEqual(calc.multiply(20, 20), 400)
self.assertEqual(calc.multiply(-1, -1), 1)
self.assertEqual(calc.multiply(-1, 1), -1)
def test_subtract(self):
self.assertEqual(calc.subtract(20, 10), 10)
self.assertEqual(calc.subtract(10, 20), -10)
self.assertEqual(calc.subtract(1, -1), 2)
self.assertEqual(calc.subtract(-1, -1), 0)
def test_division(self):
self.assertEqual(calc.division(20, 20), 1)
self.assertEqual(calc.division(-1, -1), 1)
self.assertEqual(calc.division(-1, 1), -1)
self.assertEqual(calc.division(5, 2), 2.5)
# self.assertRaises(ValueError, calc.division, 10, 0)
with self.assertRaises(ZeroDivisionError):
calc.division(20, 0)
def test_modulo(self):
self.assertEqual(calc.modulo(10, 5), 0)
self.assertEqual(calc.modulo(2, 5), 2)
with self.assertRaises(ZeroDivisionError):
calc.modulo(5, 0)
if __name__ == "__main__":
unittest.main()
# here v run the test for each method in calc.py
|
beb20ed70cebb3811ad634dd50df807008e5424c | galicminer/Tec | /TC1028/Python/Ejericicio4 Algoritmos.py | 333 | 3.84375 | 4 | print("Test de aptitud para la licencia de conducir")
print("Cuenta usted con una identificacion oficialsi/no")
iden=input()
print("ingrese su edad numericamente")
edad=int(input())
if(iden=="si")and(edad>=18):
print("esta usted habilitado para recibir licencia")
else:
print("usted no esta habilitado para recibir licencia") |
a4d2fa34c8bd70770397a64cbe0fde8386dfa56e | chris-bk-song/python-101 | /python_exercise_two.py | 359 | 4.21875 | 4 | # Step 0: Document the problem
# Prompt user to input their name and print out welcome mesage with their name
# Step 1: Setup/Configuration
name = input('What is your name? ')
name_length = len(name)
# Step 2: Result/Output
greeting = f'Welcome, {name.upper()}! \n YOUR NAME HAS {name_length} LETTERS IN IT! AWESOME!'
# Step 3: Do the work
print(greeting) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.