blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
92eeffb2750f8e8e3753e5c47fabb9a5f2d69e10 | yangxiangtao/biji | /1-pbase/day11/exercise/2.py | 449 | 3.984375 | 4 | #第一问
def print_list(L,line=False):
for x in L:
if type(x) is int:
print(x,end=' ')
else:
print_list(x)
L = [[3,5,8],10,[[13,14],15,18],20]
print_list(L,True)
# #第二问
# def sum_list(L):
# s=0
# for x in L:
# if type(x) is int:
# s += x
# else:
# s += sum_list(x)
# return s
# L = [[3,5,8],10,[[13,14],15,18],20]
# print(sum_list(L))
|
aac4c849e730db942cc4e511886f6e67c9214be2 | moonshadow31562047/tkinter_sample | /tk18.py | 234 | 3.671875 | 4 | import tkinter as tk
def print_txval():
val_en = en.get()
print(val_en)
root = tk.Tk()
en = tk.Entry()
bt = tk.Button(text="ボタン",command=print_txval)
[widget.pack() for widget in (en,bt)]
en.focus_set()
root.mainloop() |
8e2fa620161423b4d084be90b3db576ee256582b | jeffsouza01/PycharmProjects | /Ex019 - SorteandoItemLista.py | 407 | 4.1875 | 4 | '''
Exercício Python 019: Um professor quer sortear um dos seus quatro alunos para apagar o quadro.
Faça um programa que ajude ele, lendo o nome dos alunos e escrevendo na tela o nome do escolhido.
'''
import random
listaAlunos = []
for i in range(0, 4):
aluno = input(f'Digite o nome do {i+ 1}º aluno: ')
listaAlunos.append(aluno)
print(f'O Aluno sorteado foi {random.choice(listaAlunos)}.')
|
5a531a39d1a40dd1faa417e6b82287c42665dea8 | codetecht/AoC2020 | /14/14.py | 3,259 | 3.5625 | 4 | # Copyright 2020 Joseph Kularski
# Workspace for Advent of Code 2020
# Request permission before using or duplicating this code for any purpose
import re
from functools import partial
from functools import reduce
from itertools import product
# File IO
f = open("14/input.txt", "r+")
data = f.readlines()
# ReGex to extract numeric values from a string
reMem = re.compile('(\d+)')
# Convert a binary string to its base-10 value
# throws: ValueError if digits in string are not 0 or 1
# TypeError if not supplied with string arg
binToDec = partial(int, base=2)
def getInput():
input = list()
for line in data:
input.append(line.rstrip())
return input
def part1(input):
memory = {}
mask = ''
for line in input:
line = line.split()
if line[0] == 'mask':
mask = line[2]
else:
# Extract the address to which we write
addr = reMem.findall(line[0])[0]
# Convert the integer value to be written to its binary equivalent
# as a list for mutability
bin_val = list(bin(int(line[2]))[2:])
# Pad the length of the value such that its length equals the mask
while len(bin_val) < len(mask):
bin_val.insert(0, '0')
# Apply the mask to the value:
# X: Bit unchanged
# 0|1: Change value's bit to 0|1
for i, bit in enumerate(mask):
if bit != 'X':
bin_val[i] = bit
memory[addr] = binToDec(''.join(bin_val))
print(reduce(lambda x,y: x+y, memory.values()))
def part2(input):
memory = {}
mask = ''
for line in input:
line = line.split()
if line[0] == 'mask':
mask = line[2]
else:
# Extract the address to which we apply the mask
addr = reMem.findall(line[0])[0]
qbits = []
# Convert the address to binary as a list for mutability
bin_addr = list(bin(int(addr))[2:])
value = int(line[2])
# Pad the length of the address so that its length equals the mask
while len(bin_addr) < len(mask):
bin_addr.insert(0, '0')
# Apply the mask to the address:
# 0: Bit unchanged
# 1|X: Change value's bit to 1|X
for i, bit in enumerate(mask):
if bit != '0':
bin_addr[i] = bit
if bit == 'X':
qbits.append(i)
# Generate a list of all possible binary strings the same length
# as the number of X's in bin_addr
combos = list(product([0,1], repeat=len(qbits)))
# Go through each combination, replacing the X's with each combo
# of binary strings, thus generating all possible addresses
for combo in combos:
for i in range(len(combo)):
bin_addr[qbits[i]] = str(combo[i])
new_addr = binToDec(''.join(bin_addr))
memory[new_addr] = value
print(reduce(lambda x,y: x+y, memory.values()))
def main():
part1(getInput())
part2(getInput())
main()
|
988b8771875f176efbd6a5868c232aa349a6d498 | pauloALuis/LP | /SeriesDeProblemas4/pd2.py | 761 | 3.640625 | 4 | """
pd2.py
23/08/2021
"""
#2.a)
class InstrumentoMusical:
def __init__(self, nome, tipo, marca, preco):
self.nome = nome
self.tipo = tipo
self.marca = marca
self.preco = preco
self.__nota = 0 # private variable convention
#2.d)
def __init__(self) -> None:
pass
#2.c
def get_nota(self):
return self.__nota
def set_nota(self, nota):
self.__nota = nota
#2.b)
def __str__(self):
return "Instrumento Musical: \nNome : " + self.nome + "\nTipo: " + self.tipo + "\nMarca: " + self.marca + "\nPreco: "+ str(self.preco)+ "€\nNota: " + str(self.__nota)
inst = InstrumentoMusical("Guitarra", "cordas", "fender", 200)
inst.set_nota(10)
print(inst)
|
ab580ae67f1a7bfc47a27de723e5142ab9bd89a8 | dariokwo/maze-solver | /dijkstra.py | 3,625 | 4.09375 | 4 | from collections import deque
from node import Node
from pq import PQueue
def dijkstra(start, target, order: bool = False) -> list:
"""
Dijkstra Algorithm: Find Shortest path between two Nodes
input start: Start of a Linked graph
input target: Last Node to end path
input order: If set to true, track and return traversal order
return: path = Shortest path = list of connected Nodes from start to target
"""
# AVOID ANY SURPRISES
assert isinstance(start, Node) and isinstance(target, Node)
# Define containers
pq = PQueue() # Priority queue: values = [(job, priority), ... ]
visited = {} # Visited, but not explored
explored = {} # Visited and explored
# visited[Node] = (previous node, distance from previous node)
visited[start] = (None, 0)
# pq.enqueue: parameters = (Node, distance from start to this node)
pq.enqueue(start, 0)
traversal_order = deque()
total_distance = 0
while pq.size() > 0:
# Pop and explore node with smallest distance from start node
# Rem: priority = distance from start to current node
(current_node, total_distance) = pq.dequeue(return_priority=True)
# Store traversal order and stop after reaching target
if(order == True): traversal_order.append(current_node)
if current_node == target: break
# Visit all neighbors of current node
for edge in current_node.get_edges_weighted():
# edge = (neighbor, distance) for weighted graph
(neighbor, distance) = edge
new_distance = total_distance + distance
# Add to PQ if not visited
if not (neighbor in visited):
pq.enqueue(neighbor, new_distance)
visited[neighbor] = (current_node, new_distance)
# If visited, but new distance is smaller
elif not (neighbor in explored) and visited[neighbor][1] > new_distance:
# Remove from pQ and enqueue same node with new distance/priority
# Also updated the visited set
pq.remove(neighbor, visited[neighbor][1])
pq.enqueue(neighbor, new_distance)
visited[neighbor] = (current_node, new_distance)
# A Node is explored after visiting all it's neighbors
explored[current_node] = True
# Trace path from target to root
path = deque()
while target != None and target in visited:
path.appendleft(target)
target = visited[target][0]
# Return path and total distance from start to target (And traversal order if needed)
if order == True: return path, total_distance, traversal_order
return path, total_distance
if __name__ == "__main__":
# Creating a linked graph
root = Node(1)
node2 = Node(2)
root.add_edge(node2, 2)
node2.add_edge(root, 2)
node3 = Node(3)
root.add_edge(node3, 3)
node3.add_edge(root, 3)
node4 = Node(4)
node2.add_edge(node4, 4)
node4.add_edge(node2, 4)
node3.add_edge(node4, 2)
node5 = Node(5)
node3.add_edge(node5, 6)
node5.add_edge(node3, 6)
target = Node(6)
node4.add_edge(target, 5)
target.add_edge(node4, 5)
node4.add_edge(node3, 2)
print("Dijkstra Algorithm")
path, total_distance, traversal_order = dijkstra(root, target, order=True)
print("Total distance: ", total_distance)
print("Path: ", path)
print("Traversal order: ", traversal_order) |
cefc02769d051327ed6bc8ee2c57e242019ebd17 | Sheverly-Python-Programs/100-Days-of-Python | /Repository/Day_3/a_Conditional_Statement_Rollercoaster_app.py | 272 | 4.15625 | 4 | print("Welcome to the rollercoaster!")
height = int(input("What is your height in cm? "))
if height >= 120:
print("Congratulations! You can ride the rollercoaster.")
else:
print("Sorry, you are below the height requirement.\nPlease come back once you become taller.")
|
4df09f19f356160159099c67bc2fa3ff434f15f1 | nbargenda/ProjectEuler | /Python/Problem 19/Problem 19.py | 337 | 3.828125 | 4 | # DESC: How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
import calendar
count = 0
calendar = calendar.Calendar()
month = []
for i in range(1901,2001):
for m in range(1,13):
month = calendar.monthdays2calendar(i,m)
count += month[0].count((1,6))
print(count) |
c2b92b3c8b98838b527ece93ddb9979ddd2b7de3 | caitlinbaker/python_projects | /project9.py | 4,238 | 3.703125 | 4 | """
CIS 15 Project 9
Simple Blog
Caitlin Baker
"""
import json
def save_blogs(data, filename) :
with open(filename, 'w') as f :
f.write(json.dumps(data, sort_keys=True, indent=2))
def load_blogs(filename) :
with open(filename) as f :
return json.loads(f.read())
def create_user(data, username, realname, email) :
''' Create a user in a blog data structure
Args:
data - The data structure to use
username - The user's username
realname - The uers's real name
email - The users's email address.
'''
data[username] = {}
data[username]['name'] = realname
data[username]['email'] = email
data[username]['posts'] = []
def add_post(data, username, title, text) :
''' Append the post to the user's list of blog posts.
Args:
data - The blog data structure to use.
username - The user who wrote the post.
title - The title of the new post.
text - The text of the post.
'''
data[username]['posts'].append({'title' : title, 'text' : text})
def print_blogs(data, username) :
''' Print all of the blog entries for a user.
Args:
data - The blog data structure to use.
username - The user to print.
'''
for blog in data[username]['posts'] :
print ('Title:', blog['title'])
print ('Text:', blog['text'])
def list_users(data):
''' Lists every username in the data structure
Args: data - the blog data structure to use
Returns a list of usernames
'''
usernames = []
for username in data:
usernames.append(username)
return usernames
def user_summary(data, username):
''' Returns a list of post post title for the specified username
Args: data- the blog data sturcture to use
username - the nmae of the user to give summary for
Returns a list of titles
'''
post_titles = []
try:
for titles in data[username]['posts']:
post_titles.append(titles['title'])
except KeyError:
print("Sorry, user does not exist.")
return
return post_titles
def update_user_info(data, username, new_name, new_email):
''' Function to update name or email for a specific username
Args: data - the blog data structure to use
username - username of the user to update_user_info
new_name - the new name to update with
new_email - the new email to update with
Returns nothing
'''
try:
if new_name != None and new_email != None:
data[username]['name'] = new_name
data[username]['email'] = new_email
elif new_email != None and new_name == None:
data[username]['email'] = new_email
elif new_email == None and new_name != None:
data[username]['name'] = new_name
else:
return
except KeyError:
print("Sorry, user does not exist.")
return
def delete_post(data, username, post_number):
'''
Deletes the given post number for a specified user
Args: data - the blog data structure to use
username - name of the user to delete post from
post_number - the index number of the desired post to delete
Returns the deleted post
'''
try:
try:
deleted = data[username]['posts'].pop(post_number)
except IndexError:
print("Sorry, post does not exist.")
return
except KeyError:
print("Sorry user does not exist.")
return
return deleted
def main() :
bloggers = load_blogs('blog_data.json')
#create_user(bloggers, 'fil', 'Fillip Foo', 'fil@foo.com')
#add_post(bloggers, 'fil', 'Welcome to my Blog', 'This is my first post')
#print_blogs(bloggers, 'ada')
#print_blogs(bloggers, 'fil')
test = list_users(bloggers)
print(test)
test2 = user_summary(bloggers, 'mike')
print(test2)
update_user_info(bloggers, 'mike', 'Mike M', 'mike@youmail.com')
deleted = delete_post(bloggers, 'fil', 2)
print(deleted)
save_blogs(bloggers, 'blog_data.json.out')
if __name__ == '__main__' :
main()
|
d582c5613245b3e3341ed8a94185cd0862edab94 | dkota1992/HackerRank-Python | /Fibonocci modify.py | 192 | 3.515625 | 4 | k = map(int,raw_input().split(" "))
def fibby(k1,k2,n):
count = 2
while True:
k1,k2 = k2,k1+k2**2
count += 1
if count == n: return k2
print fibby(*k)
|
fc6faa0d10e889d22ff499eb940a53aad0c41c9d | igortereshchenko/amis_python | /km73/Zeleniy_Dmytro/4/task6.py | 532 | 4.125 | 4 | start_row = int(input("Enter start row: "))
start_column = int(input("Enter start column: "))
finish_row = int(input("Enter finish row: "))
finish_column = int(input("Enter finish column: "))
if start_row > 0 and start_row <= 8 and start_column > 0 and start_column <= 8 and finish_row > 0 and finish_row <= 8 and finish_column > 0 and finish_column <= 8:
if start_row == finish_row or start_column == finish_column:
answer = "Yes"
else:
answer = "No"
else:
answer = "NOT CORRET DATA!"
print(answer) |
310153d01a647229267e1bc6f301db23f900fc9c | kyooryoo/think-python | /9_6.py | 316 | 3.640625 | 4 | def is_abecedarian(s):
for index in range(len(s)-1):
if s[index] > s[index+1]:
return False
return True
count = 0
fin = open('words.txt')
for line in fin:
word = line.strip().strip(' ')
if is_abecedarian(word):
count += 1
print("there are {} abecedarian".format(count)) |
5e94d8e0a73d9622274230b0067105616c71b606 | thiagosm/aiotdlib | /aiotdlib_generator/parser/utils.py | 301 | 3.765625 | 4 | import re
def upper_first(s: str):
return s[:1].upper() + s[1:]
def lower_first(s: str):
return s[:1].lower() + s[1:]
def snake_case(s: str):
if not str:
return ""
s = re.sub(r'(.)([A-Z][a-z]+)', r'\1_\2', s)
return re.sub(r'([a-z0-9])([A-Z])', r'\1_\2', s).lower()
|
07c0673f558f658facf5fb5012be0f3c8ec15651 | league-python-student/level0-module0-Skywing609 | /_03_print_and_popups/_c_world_domination.py | 835 | 4.21875 | 4 | from tkinter import messagebox, simpledialog, Tk
# Create an if-main code block, *hint, type main then ctrl+space to auto-complete
if __name__ == '__main__':
# Make a new window variable, window = Tk()
window = Tk()
# Hide the window using the window's .withdraw() method
window.withdraw()
# 1. Ask the user if they know how to write code.
q =input('Do you know how to write code? y/n')
if q == 'y':
print(''+ q +'')
messagebox.showinfo('title','YOU WILL RULE THE WORLD!')
# 2. If they say "yes", tell them they will rule the world in a message box pop-up.
# 3. Otherwise, tell them to sign up for classes at The League in an error box pop-up.
if q == 'n':
messagebox.showerror('ERROR','SIGN UP FOR CLASSES AT THE LEAGUE!')
# Run the window's .mainloop() method
|
1845d484d65c3d093709a18661e3831f02dfe43a | jmbarrie/nth-puzzle-py | /puzzle.py | 2,688 | 4.1875 | 4 | class Puzzle:
def __init__(self):
puzzle = None
def get_puzzle(self):
"""
Returns the current puzzle.
"""
return self.puzzle
def set_puzzle(self, puzzle_index1, puzzle_index2, new_puzzle_value):
"""
Sets the value of the puzzle
Args:
puzzle_index1 (int): First index of the puzzle tuple
puzzle_index2 (int): Second index of the puzzle tuple
new_puzzle_value (int): Value to update
"""
self.puzzle[puzzle_index1][puzzle_index2] = new_puzzle_value
def print_puzzle(self):
"""
Outputs the current puzzle.
"""
for row in self.puzzle:
print(*row, sep=' ')
def create_default_puzzle(self):
"""
Selection 1: Generates a default puzzle for the user.
"""
self.puzzle = [[1, 2, 3],
[4, 0, 6],
[7, 5, 8]
]
def create_custom_puzzle(self):
"""
Selection 2: Allows user to define a custom puzzle.
"""
custom_puzzle = []
print('Enter your puzzle, use a zero to represent the blank, and exit to'
+ 'complete your custom puzzle')
while True:
user_selection = \
input('Enter the row, use space or tabs between numbers\t')
if user_selection == 'exit':
break
else:
row_list = user_selection.split(" ")
row_list = [int(i) for i in row_list]
custom_puzzle.append(row_list)
continue
self.puzzle = custom_puzzle
print()
self.print_puzzle()
print()
def get_index_value(self, puzzle_index1, puzzle_index2):
"""
Returns the contents at tuple index.
Args:
puzzle_index1 (int): First index of the puzzle tuple
puzzle_index2 (int): Second index of the puzzle tuple
"""
return self.puzzle[puzzle_index1][puzzle_index2]
def get_blank_space_index(self):
"""
Finds and returns the index of the blank space.
"""
blank_space_indices = []
for index, list in enumerate(self.puzzle):
if 0 in list:
blank_space_indices.extend((index, list.index(0)))
return blank_space_indices
def get_puzzle_array_size(self):
"""
Returns the size of the puzzle indices, and the length of each list.
"""
list_size = len(self.get_puzzle()[0])
puzzle_size = len(self.get_puzzle())
return [puzzle_size, list_size] |
b4c129e7cee824b63a244020efffcf2389a43618 | MrHamdulay/csc3-capstone | /examples/data/Assignment_6/mnbpan001/question1.py | 968 | 4.15625 | 4 | """Program to store list of strings and output it right-aligned with the longest string
Pankaj Munbodh
20 April 2014"""
#Create list of strings
str_list=[]
get_string = input("Enter strings (end with DONE):\n")
if get_string !='DONE':
str_list.append(get_string)
#sentinel loop keeps asking for input until user enters'DONE'
while (get_string=='DONE')==False:
get_string = input("")
if get_string!='DONE':
str_list.append(get_string)
#Width of character of maximum length is found
width=max(len(word) for word in str_list)
print()
print("Right-aligned list:")
#List is iterated through and each character is printed right-justified in field width of maximum with found earlier
for word in str_list:
print(word.rjust(width))
#output for exception
else:
print()
print("Right-aligned list:") # if-else statement to cater for exception if user types in "DONE" right at start |
b7aa3d4a026c307a2bb690b840bab426ac6ea525 | eva-montgomery/2019-11-function-demo | /longest_string.py | 394 | 4.3125 | 4 | # 3. Find the shortest String
# Write a function shortest that accepts a List of Strings as an argument.
# It should return the shortest String in the List.
def longest(lst):
the_longest = lst[0]
for word in lst:
if len(word) > len(the_longest):
the_longest = word
return the_longest
print(longest(["horse", "pig", "dog","flamingo"]))
|
8911f03237f8a4ea774d2b5f84550896df1400b7 | NAU-CFL/Python_Learning_Source | /scripts/coin_change_exercise.py | 1,504 | 4.09375 | 4 | # Coin Change Exercise Program
import random
# Program greeting
print('The purpose of this exercise is to enter a number of coin values that add up to a displayed target value.')
print('Enter coins values as 1-penny, 5-nickel, 10-dime, and 25-quarter.')
print('Hit return/enter after the last entered coin value.')
print('-'*15)
# Initialize
terminate = False
empty_str = ""
# Start the Game
while not terminate:
amount = random.randint(1,99)
print("Enter coins that add up to " + str(amount) + " cents, one per line.")
game_over = False
total = 0
while not game_over:
valid_entry = False
while not valid_entry:
if total == 0:
entry = input('Enter first coin: ')
else:
entry = input('Enter next coin: ')
if entry in (empty_str, '1', '5', '10', '25'):
valid_entry = True
else:
print('Invalid entry')
if entry == empty_str:
if total == amount:
print('Correct!')
else:
print('Sorry - you only entered ' + str(total) + ' cents.')
game_over = True
else:
total = total _ int(entry)
if total > amount:
print('Sorry - total amount exceeds ' + str(amount) + ' cents.')
if game_over:
entry = input('\nTry Again (y/n)?: ')
if entry == 'n':
terminate = True
print('Thanks for playing ... Goodbye!')
|
d3cd756f38011cd2d5be2a4fface26da8015ab6b | jacob-02/OpenCV_Studies | /draw.py | 1,405 | 3.890625 | 4 | import cv2 as cv
import numpy as np
img = np.zeros((500, 500, 3), dtype='uint8')
img[200:300, 300:400] = 0, 255, 255 # This is the array values for the color green
cv.rectangle(img, (0, 0), (250, 250), (255, 255, 0),
thickness=-1) # Draws a rectangle on the image "img", from point (0,0) to (250,250) of the color from the array (255,255,0) with a line of thickness 2 or -1 which fills the rectangle
cv.rectangle(img, (0, 0), (img.shape[1] // 2, img.shape[0] // 2), (250, 250, 200), thickness=-1) # This is used to cut the image in half and stuff like that
cv.circle(img, (250, 250), 40, (0, 250, 0), thickness=2) # This is used to create the circle on the image following almost the same pattern as the rectangle
cv.line(img, (0, 0), (300, 300), (0, 100, 0), thickness=4) # This follows the exact same syntax as the rectangle which kinda makes sense and makes this function redundant as we could actually just use the rectangle wala with the appropriate thickness
cv.putText(img, "Hello darkness smile friend", (0, 300), cv.FONT_HERSHEY_TRIPLEX, 1.0, (0, 255, 0), thickness=2) # This is used to put texts on the screen. Basically I have to google a bit for values regarding the font face and if I want a specific color that too. The syntax for the functions are just popping up due to the IDE being sick. So this is all pretty chill
cv.imshow('Random', img)
cv.waitKey(0)
|
08babcf47ab5bdc74edde5bcd166e99ab5bf6149 | prodrigues07/paulo-victor-poo-p7-info | /Atividades para Presença/Atividade 3 (05 de Abril)/triangulo.py | 400 | 3.9375 | 4 | a = float(input('Digite o valor do Lado A: '))
b = float(input('Digite o valor do Lado B: '))
c = float(input('Digite o valor do Lado C: '))
if (a == b and b == c and a==c):
print('Triângulo do Tipo Equilátero')
elif(a == b and a != c and b != c) or (b == c and a != c and b != a) or (c == a and c != b):
print('Triângulo do Tipo Isóceles')
else:
print('Triângulo do Tipo Escaleno') |
9ce626806c272f73f409a72d452b045e3a0e384f | papostolopoulos/code_exercises | /playground.py | 1,906 | 4.5 | 4 | # coding: utf-8
# 20180425
# BRACKETS https://py.checkio.org/en/mission/brackets/
# You are given an expression with numbers, brackets and operators.
# For this task only the brackets matter. Brackets come in three flavors:
# "{}" "()" or "[]". Brackets are used to determine scope or to restrict
# some expression. If a bracket is open, then it must be closed with a closing
# bracket of the same type. The scope of a bracket must not intersected by
# another bracket. In this task you should make a decision, whether to correct
# an expression or not based on the brackets. Do not worry about operators
# and operands.
#
# Input: An expression with different of types brackets as a string (unicode).
# Output: A verdict on the correctness of the expression in boolean (True or False).
#
# Example:
# checkio("((5+3)*2+1)") == True
# checkio("{[(3+1)+2]+}") == True
# checkio("(3+{1-1)}") == False
# checkio("[1+1]+(2*2)-{3/3}") == True
# checkio("(({[(((1)-2)+3)-3]/3}-3)") == False
# checkio("2+3") == True
def brackets(str):
symbols = "(){}[]"
open_symbols = "({["
close_symbols = ")}]"
newStr = ""
for y in str:
if y in symbols: newStr += y
if len(newStr) == 0: return True
if len(newStr) % 2 != 0: return False
while len(newStr) != 0:
for x in range(1, len(newStr)):
if newStr[x] in close_symbols:
if newStr[x - 1] in open_symbols and close_symbols.find(newStr[x]) == open_symbols.find(newStr[x-1]):
newStr = newStr[0:x-1] + newStr[x+1:]
break
else:
return False
return True
print(brackets("((5+3)*2+1)")) # == True
print(brackets("{[(3+1)+2]+}")) # == True
print(brackets("(3+{1-1)}")) # == False
print(brackets("[1+1]+(2*2)-{3/3}")) # == True
print(brackets("(({[(((1)-2)+3)-3]/3}-3)")) # == False
print(brackets("2+3")) # == True
|
634a5e7b23db3baa7fec53f1100f6619b7cc9a5e | xiaoyu-meng/python27_test001 | /zidian_way_001.py | 927 | 3.8125 | 4 | # -*- coding: utf-8 -*-
# 字典 键不能是列表,而且不可以重复,键值可以是列表,可以重复
phonebook={'Alice':'1234','zhangsan':'8754','Cecil':'3258'}
d1 = {'spam':2,"ham":1,'eggs':3}
d2={'food':{'spam':2,"ham":1,'eggs':3}}
d3={}
print phonebook['Alice']
items=[('name','Gumby'),('age',42)]
d=dict(items)
print d
print d['name']
d4=dict(name='Gumby',age=42)
print 'd4:%s'% d4
phonebook['zhangsan']=5555
print phonebook
del phonebook['zhangsan']
print phonebook
print 'Alice' in phonebook
print 'Alices' in phonebook
phonebook['abc'] = 5555
print phonebook
# 字典 字符串的格式化
print "Cecil's phone number is:%(Cecil)s" % phonebook
template='''<html>
<head><title>%(title)s</title></head>
<body>
<h1>%(title)s</h1>
<p>%(text)s</p>
</body></html>'''
data={'title':"My Home Page",'text':'Welcome to my home page'}
print template % data
|
86b40d9b9ccf13b358fc3fb48a947d41bde65130 | nixis-institute/practice | /python/bhawna/third.py | 130 | 3.8125 | 4 | a= input("enter the first number")
b= input("enter the second number")
c=a*b
print(type(c))
print("the multiplication is", c ) |
e9725a992d0c6fcf82646fcec06cc3118fab6a19 | KFranciszek/Python-Dla-Kazdego | /pobierz-i-zwroc.py | 662 | 3.796875 | 4 | # pobierz i zwroc
# demonstruje parametry i wartosci zwrotne
def display(message):
print(message)
def give_me_five():
five = 5
return five
def ask_yes_no(question):
"""Zadaj pytanie, na ktore mozna podpowiedz tak lub nie"""
respone = None
while respone not in ("t","n"):
respone = input(question).lower()
return respone
# main
display("To wiadomosc dla Ciebie.\n")
number = give_me_five()
print("oto co otrzymalem z funkcji give_me_five()", number)
answer = ask_yes_no("\nProsze wprowadzic 't' lub 'n': ")
print("dziekuje za wprowadzenie", answer)
input("\n\nAby zakończyć program, naciśnij klawisz Enter.") |
f9f8b6b34150b011809ea592deac31ae23f7d622 | rahuldbhadange/Python | /__Python/iter.py | 512 | 3.953125 | 4 | from collections import Iterable
l = [[[1,2,5,9],[3,8]],[5,0,7],[4,2,6]]
def flatten(items):
"""Yield items from any nested iterable; see Reference."""
for x in items:
if isinstance(x, Iterable):
for sub_x in flatten(x):
yield sub_x
else:
yield x
res = flatten(l)
print(res)
result = []
for i in res:
result.append(i)
print(result)
import operator
from functools import reduce
print(reduce(operator.concat, l))
|
be3b75bd31ba931168af49e7c43e38fef62425c3 | sarthakbansalgit/basic-python- | /usingCSVmodule.py | 261 | 3.578125 | 4 | import csv
def write():
p = open("example.csv",'w')
w = csv.writer(p)
title= ["Name","Class","Roll"]
details= ["Sarthak","11","25"]
w.writerows(title)
w.writerows(details)
for i in details:
w.writerows(i)
p.close
write()
|
72c162fbbb2b658761c178a356ea2b0548c633e8 | adeelahuma/getting_my_hands_dirty_with_code | /python/data_structures/sorting_algos/selection_sort.py | 297 | 3.796875 | 4 |
arr = [4,5,2,3,1]
print ('unsorted', arr)
for i in range(len(arr)):
min_idx = i
for j in range(i+1, len(arr)):
if arr[min_idx] > arr[j] :
min_idx = j
#arr[i] = min_elem
temp = arr[i]
arr[i] = arr[min_idx]
arr[min_idx] = temp
print('sorted', arr)
|
960ceea2ba4dab5c69e444c216906b51ff4cc9ea | Moby5/myleetcode | /python/400_Nth_Digit.py | 1,776 | 3.765625 | 4 | #!/usr/bin/env python
# coding=utf-8
"""
# not understood yet
http://bookshadow.com/weblog/2016/09/18/leetcode-nth-digit/
400. Nth Digit
Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
Note:
n is positive and will fit within the range of a 32-bit signed integer (n < 2^31).
Example 1:
Input:
3
Output:
3
Example 2:
Input:
11
Output:
0
Explanation:
The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.
题目大意:
给定一个无穷整数序列1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... 求序列的第n位数字。
注意:
n是正数并且范围在32位带符号整数之内(n < 2^31)
解题思路:
将整数序列划分为下列区间:
1 1-9
2 10-99
3 100-999
4 1000-9999
5 10000-99999
6 100000-999999
7 1000000-9999999
8 10000000-99999999
9 100000000-99999999
然后分区间求值即可。
"""
class Solution(object):
def findNthDigit(self, n):
"""
:type n: int
:rtype: int
"""
for i in range(9):
# print 'i:', i
d = 9 * 10 ** i
# print 'd:', d
if n <= d * (i + 1): break
n -= d * (i + 1)
# print 'n:', n
n -= 1
# print 'n:', n
return int(str(10**i + n / (i + 1))[n % (i + 1)])
def findNthDigit_ref(self, n):
"""
:type n: int
:rtype: int
"""
for i in range(9):
d = 9 * 10 ** i
if n <= d * (i + 1): break
n -= d * (i + 1)
n -= 1
return int(str(10**i + n / (i + 1))[n % (i + 1)])
test = Solution()
nums = [3, 11, 100]
for n in nums:
print n, test.findNthDigit(n)
|
630e1f44c1d6d298de515180ba5f74b0422f8e03 | 4workspace/Python-calisma-notlari | /12_list_tuple_set_dic_farklari.py | 977 | 3.703125 | 4 | # list: [] ile gösterilir.
# tuple: () ile gösterilir.
# set: ([]) ile gösterilir.
# dictionary: {} ile gösterilir.
list1 = ["Python","C/C++","C#"]
list1[0] = "Artifical" # eleman değiştirilebilir.
print(list1)
tuple1 = ("Python","C/C++","C#")
# tuple1[0] = "Artificial" # tuple da eleman değiştirilemez.
tuple1 = ("Matlab","Simulink","Qt") # tuple da sıfırdan eleman atanabilir
print(tuple1)
set1 = set(["Python","C/C++","C#"]) # set'te elemanlar karışık dizlir. Her derleme de sıraları değişir
# set1[0] = "Artificial" # set'te eleman değiştirilemez
set1 = set(["Matlab","Simulink","Qt","Qt"]) # set bildiğimiz kümeler konusu bu yüzden bir kümede aynı eleman 1 kere bulunabilir. Fazla Qt yazılmaz
print(set1)
dict1 = {1:"Python", 2:"C/C++", 3:"C#"}
dict1[0] = "Artificial"
print(dict1 )
print(type(list1))
print(type(tuple1))
print(type(set1))
print(type(dict1)) |
522ae9363edbb4c7e810e176644fa857d6487457 | chandramohank/Logical-Programes | /Python/powerset.py | 396 | 3.859375 | 4 | import math
def powerset(array):
powers=[]
total=int(math.pow(2,len(array)))
for i in range(0,total):
temp=[]
num="{0:b}".format(i)
while len(num)<len(array):
num='0'+num
for j in range(0,len(num)):
if num[j]=='1':
temp.append(array[j])
powers.append(temp)
return powers
print(powerset([3,4,5,6]))
|
7c42b4fba1993eb34d075b2df398430fabfed275 | haiy/test_project | /python_lib/leetcode/remove_duplicate_from_sorted_array.py | 547 | 3.859375 | 4 | #!/usr/bin/python
#Gven a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
#Do not allocate extra space for another array, you must do this in place with constant mem- ory.
#For example, Given input array A = [1,1,2],
#Your function should return length = 2, and A is now [1,2].
def remove (l):
idx = 0
for i in l[1:]:
if i != l[idx]:
idx += 1
l[idx] = i
return idx + 1
l=[1,2,2,3,4, 4]
print l[:remove(l)]
l=[1,1,2,3]
print l[:remove(l)]
|
146c3709d235eb27de96dfc26f30f74f7559bf34 | MiroVatov/Python-SoftUni | /Python Fundamentals 2020 - 2021/Final Exams Practice/03. Inbox Manager.py | 933 | 3.671875 | 4 | emails_dict = {}
while True:
command = input()
if command == 'Statistics':
break
token = command.split('->')
action = token[0]
if action == 'Add':
username = token[1]
if username in emails_dict:
print(f'{username} is already registered')
else:
emails_dict[username] = []
elif action == 'Send':
username = token[1]
email = token[2]
emails_dict[username].append(email)
elif action == 'Delete':
username = token[1]
if username in emails_dict:
del emails_dict[username]
else:
print(f'{username} not found!')
print(f'Users count: {len(emails_dict)}')
sorted_dict = dict(sorted(emails_dict.items(), key=lambda x: (-len(x[1]), x[0])))
for user, emails in sorted_dict.items():
print(f'{user}')
for em in emails:
print(f' - {em}')
|
3c35e71c5b6b561d54f6193479d5ea612bd9e2fd | ryuo07/C4TB | /session8/exercises/list_print_with_for.py | 156 | 4 | 4 | a = ['sport', 'lol','bts']
print(a)
for i in range(3):
b = input('one more hobby: ')
a.append(b)
print(a)
d = a
for e in d:
print(e) |
495572ea0f937e15794f2ac37723c838c75c8bab | jenyafross/patterns_py | /behavioural/Command.py | 1,657 | 3.53125 | 4 | from abc import ABC, abstractmethod
class Command:
@abstractmethod
def execute(self):
raise AttributeError('Method is not implement')
@abstractmethod
def undo(self):
raise AttributeError('Method is not implement')
class EmptyCommand(Command):
def execute(self):
print('Command is not set')
def undo(self):
print('Nothing to do')
class Light:
def on(self):
print(f'Light {id(self)} turned on')
def off(self):
print(f'Light {id(self)} turned off')
class LightOnCommand(Command):
def __init__(self, light: Light):
self.light = light
def execute(self):
self.light.on()
def undo(self):
self.light.off()
class LightOffCommand(Command):
def __init__(self, light):
self.light = light
def execute(self):
self.light.off()
def undo(self):
self.light.on()
class Remote:
def __init__(self, slot_num):
cmnd = EmptyCommand()
self.commands = [cmnd] * slot_num
self.undos = []
def set_command(self, command: Command, slot):
self.commands[slot] = command
def execute(self, slot):
self.commands[slot].execute()
self.undos.append(self.commands[slot].undo)
def undo(self):
if self.undos:
command = self.undos.pop()
command()
if __name__ == '__main__':
l1 = Light()
remote = Remote(10)
remote.set_command(LightOnCommand(l1), 0)
remote.set_command(LightOffCommand(l1), 1)
remote.execute(0)
remote.execute(1)
remote.execute(2)
remote.undo()
remote.undo()
remote.undo()
|
4c482f0ff3c74e590cc5b4c8fc289201f6632b60 | dmaisano/NJIT-CS | /CS-288/homework-05/data.py | 341 | 3.640625 | 4 | # python script to generate unique data for the sorting algorithms
import sys
import random
size = 100000000
if len(sys.argv) > 1:
size = int(sys.argv[1])
data = random.sample(range(size), size)
dataFile = open("data.txt", "w")
print("populating data.txt with %d integers" % size)
for i in data:
dataFile.write(str(i) + "\n")
|
a071341315027fd981b0d06976733c5d332eeee8 | aanguss/leetcode | /lc_python/numIslandsDFS.py | 2,408 | 3.71875 | 4 | # https://leetcode.com/explore/interview/card/amazon/78/trees-and-graphs/894/
##
# Given a 2d grid map of '1's (land) and '0's (water),
# count the number of islands. An island is surrounded by water
# and is formed by connecting adjacent lands horizontally or
# vertically. You may assume all four edges of the grid are all
# surrounded by water.
##
# Example 1
# Input: grid = [
# ["1","1","1","1","0"],
# ["1","1","0","1","0"],
# ["1","1","0","0","0"],
# ["0","0","0","0","0"]
# ]
# Output: 1
##
# Example 2
# Input: grid = [
# ["1","1","0","0","0"],
# ["1","1","0","0","0"],
# ["0","0","1","0","0"],
# ["0","0","0","1","1"]
# ]
# Output: 3
from typing import List
class Solution:
def __dfs(self, grid: List[List[str]], row: int, col: int):
grid[row][col] = '0'
if (row - 1 >= 0):
if (grid[row - 1][col] == '1'):
self.__dfs(grid, row - 1, col)
if (row + 1 < len(grid)):
if (grid[row + 1][col] == '1'):
self.__dfs(grid, row + 1, col)
if (col - 1 >= 0):
if (grid[row][col - 1] == '1'):
self.__dfs(grid, row, col - 1)
if (col + 1 < len(grid[0])):
if (grid[row][col + 1] == '1'):
self.__dfs(grid, row, col + 1)
def numIslands(self, grid: List[List[str]]) -> int:
if not grid:
return 0 # no islands since grid is empty
islandCount = 0
for row in range(len(grid)):
for col in range(len(grid[0])):
if (grid[row][col] == '1'):
islandCount += 1
self.__dfs(grid, row, col)
return islandCount
grid1 = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
] # should return 1
grid2 = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
] # should return 3
grid3 = [["1","0","1","1","1"],["1","0","1","0","1"],["1","1","1","0","1"]] # should return 1
s = Solution()
islands = s.numIslands(grid1)
print(f"Number of islands on grid1 = {islands}")
islands = s.numIslands(grid2)
print(f"Number of islands on grid2 = {islands}")
islands = s.numIslands(grid3)
print(f"Number of islands on grid3 = {islands}") |
ffe3f63d0a6537a81f0852942c42d2c390308ba2 | bitngu/Data-Structures-Algorithm | /Python/Stacks & Queues & Linked List/code.py | 7,558 | 4.0625 | 4 |
"""Bi Nguyen, 2 Feb 2019, ECS 32B Section: A05
Assuming the Node class and the Node2 class will be imported in order to run the code"""
#Question 1
class QueueX:
"""Implement the Queue ADT, using a list such that the rear of the queue is at the end of the list."""
def __init__(self):
self.items = []
def isEmpty(self):
return len(self.items) == 0
def enqueue(self, item):
self.items.append(item)
def dequeue(self):
self.items.pop(0)
def size(self):
return len(self.items)
#Question 2: Slice Method
class UnorderedList:
def __init__(self):
self.head = None
def isEmpty(self):
return self.head == None
def add(self,item):
temp = Node(item)
temp.setNext(self.head)
self.head = temp
def size(self):
current = self.head
count = 0
while current != None:
count = count + 1
current = current.getNext()
return count
def search(self, item):
current = self.head
found = False
while current != None and not found:
if current.getData() == item:
found = True
else:
current = current.getNext()
return found
def remove(self,item):
current = self.head
previous = None
found = False
while not found:
if current.getData() == item:
found = True
else:
previous = current
current = current.getNext()
if previous == None:
self.head = current.getNext()
else:
previous.setNext(current.getNext())
def slice(self,start,stop):
"""Implement a slice method for the UnorderedList class. It should take two parameters, start and stop,
and return a copy of the list starting at the start position and going up to but not including the stop position"""
#count = 0
copy = []
curr = self.head
while curr != None:
copy.insert(0,curr.getData())
curr = curr.getNext()
newslice = UnorderedList()
for i in range(start,stop):
newslice.add(copy[i])
return newslice
# This is if the out put is the same way it was added it in
# while count < stop - 1:
# current = current.getNext()
# count += 1
# if count >= start:
# copy.insert(0, current.getData())
# newnode = UnorderedList()
# for items in copy:
# newnode.add(items)
#Question 3 : Linked Stack
class Stack:
"""Implement a stack using linked lists."""
def __init__(self):
self.count = 0
self.head = None
def push(self, item):
temp = Node(item)
curr = self.head
if self.count > 0:
while curr != None:
prev = curr
curr = curr.getNext()
prev.setNext(temp)
else:
self.head = temp
self.count += 1
def size(self):
return self.count
def isEmpty(self):
return self.head == None
def peek(self):
return self.head.getData()
def pop(self):
count = 0
curr = self.head
while count < self.count - 1:
prev = curr
curr = curr.getNext()
count += 1
if self.count == 1:
item = self.head.getData()
self.head = self.head.getNext()
elif (self.count > 1):
item = prev.getNext().getData()
prev.setNext(curr.getNext())
return item
#Question 4: Linked Queue
class Queue:
"""Implement a queue using linked lists."""
def __init__(self):
self.head = None
self.count = 0
def enqueue(self,item):
temp = Node(item)
temp.setNext(self.head)
self.head = temp
self.count += 1
def dequeue(self):
count = 0
curr = self.head
while count < self.count - 1:
prev = curr
curr = curr.getNext()
count += 1
if self.count == 1:
item = self.head.getData()
self.head = self.head.getNext()
else:
item = prev.getNext().getData()
prev.setNext(curr.getNext())
return item
def size(self):
return self.count
def isEmpty(self):
return self.head == None
#Question 5: Linked Dequeue
class Dequeue:
"""Implement a deque using linked lists."""
def __init__(self):
self.head = None
self.count = 0
def addRear(self,item):
temp = Node(item)
temp.setNext(self.head)
self.head = temp
self.count += 1
def addFront(self,item):
temp = Node(item)
if self.head == None:
self.head = temp
else:
curr = self.head
while curr != None:
prev = curr
curr = curr.getNext()
if curr == None:
prev.setNext(temp)
self.count += 1
def size(self):
return self.count
def isEmpty(self):
return self.head == None
def removeFront(self):
count = 0
curr = self.head
while count < self.count - 1:
prev = curr
curr = curr.getNext()
count += 1
if self.count == 1:
item = self.head.getData()
self.head = self.head.getNext()
else:
item = prev.getNext().getData()
prev.setNext(curr.getNext())
self.count -= 1
return item
def removeRear(self):
item = self.head.getData()
self.head = self.head.getNext()
self.count -= 1
return item
#Question 6: Dequeue -> Double Linked List
class Dequeue2:
"""Each node has a reference to the next node (commonly called next) as well as a reference to the preceding node (commonly called back).
The head reference also contains two references, one to the first node in the linked list and one to the last"""
def __init__(self):
self.head = None
self.count = 0
def addFront(self, item):
temp = Node2(item)
if self.head == None:
self.head = temp
else:
curr = self.head
while curr != None:
prev = curr
curr = curr.getNext()
prev.setNext(temp)
prev.getNext().setPrev(prev)
self.count += 1
def addRear(self, item):
temp = Node2(item)
temp.setNext(self.head)
if self.head !=None:
temp.getNext().setPrev(temp)
self.head = temp
self.count += 1
def removeFront(self):
if self.count > 1:
curr = self.head
while curr != None:
prev = curr
curr = curr.getNext()
item = prev.getData()
prev.getPrev().setNext(curr) # -> Null
prev.getPrev().setPrev(prev.getPrev().getPrev())
else:
item = self.head.getData()
self.head = None
self.count -=1
return item
def removeRear(self):
item = self.head.getData()
self.head = self.head.getNext()
self.head.setPrev(None)
self.count -= 1
return item
def isEmpty(self):
return self.head == None
def size(self):
return self.count
|
679b072d60a2181017c211baaacff965002553e2 | alcoccoque/Homeworks | /hw1/ylwrbxsn-python_online_task_1_exercise_2/task_1_ex_2.py | 1,437 | 4.0625 | 4 | """01-Task1-Task2
Write a Python-script that performs the standard math functions on the data. The name of function and data are
set on the command line when the script is run.
The script should be launched like this:
$ python my_task.py add 1 2
Notes:
Function names must match the standard mathematical, logical and comparison functions from the built-in libraries.
The script must raises all happened exceptions.
For non-mathematical function need to raise NotImplementedError.
Use the argparse module to parse command line arguments. Your implementation shouldn't require entering any
parameters (like -f or --function).
"""
import operator
import math
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
# parser.add_argument('func', type=str, help="Use only *, /, +, -")
parser.add_argument('func', type=str, help="Use only *, /, +, -")
parser.add_argument('arguments', nargs='+')
def calculate(args):
func = args.func
string_math = 'math.' + func + '(' + ','.join(args.arguments[:]) + ')'
string_operator = 'operator.' + func + '(' + ','.join(args.arguments[:]) + ')'
if func in dir(math):
return eval(string_math)
elif func in dir(operator):
return eval(string_operator)
raise NotImplementedError
def main():
args = parser.parse_args()
print(calculate(args))
if __name__ == '__main__':
main()
|
d1ef6d326a20a6b2e40c9aeed9a633b11ec071df | Lubright/Python_298_Example | /ex_1401.py | 804 | 4.03125 | 4 |
def isFloat(num):
try:
float(num)
except:
return False
else:
return True
def isInt(num):
try:
int(num)
except:
return False
else:
return True
line = input()
result_int = 1
result_float = 1
cnt_int = 0
cnt_float = 0
while line != 'q':
if isInt(line):
result_int *= int(line)
cnt_int += 1
elif isFloat(line):
result_float *= float(line)
cnt_float += 1
elif line == 'q':
break
line = input()
if cnt_float == 0:
result_float = 0
elif cnt_int == 0:
result_int = 0
print('{:.2f}'.format(result_float))
print(result_int)
if result_float > result_int:
print('Float > Int')
elif result_float < result_int:
print('Float < Int')
else:
print('Float = Int')
|
94c090f854bb037f3a2bfabf98ca7a47e105d4a5 | dieptran43/Python_public | /codes/comments.py | 432 | 3.765625 | 4 |
# Single line comments starts with #
#This is my first Python program
# Multi lines: 3 single quotes
'''
A tuple is a collection which is ordered and unchangeable.
In Python tuples are written with round brackets.
'''
# -----------------------
# This is a
# multi-line
# comments
# -----------------------
"""
LinuxThingy version 1.6.5
Parameters:
-t (--text): show the text interface
-h (--help): display this help
""" |
5690802f3456d47b2dfccb03008dc7762e8bd5b3 | gimyoni/CodeUp | /Py/1271.py | 133 | 3.546875 | 4 | a = input()
num = list(map(int, input().split()))
max_num = 0
for n in num:
if(n > max_num):
max_num = n
print(max_num)
|
2bcc66b5706ce64a0367b66f9b0aaf917fc20032 | housseinihadia/HackerRank-Solutions | /Security/01 - Functions/05 - Security Permutations.py | 464 | 3.5 | 4 | # ========================
# Information
# ========================
# Direct Link: https://www.hackerrank.com/challenges/security-tutorial-permutations/problem
# Difficulty: Easy
# Max Score: 10
# Language: Python
# ========================
# Solution
# ========================
def permutation():
n = input()
values = list(map(int, input().split()))
for i, n in enumerate(values):
print(values[values[i] - 1])
permutation()
|
7132a1219c0b2bcce7cc2e49fe2ff5e385072a23 | vikashcodes/Python.py | /Lists/list_ofword.py | 224 | 4.03125 | 4 | lst = [x for x in input("Enter words : ").split()]
max = 0
w = ""
for word in lst:
if len(word) > max:
max = len(word)
w = word
print("Word of max length is {} with lenght {}".format(w, max))
|
db0060418160f11b525a9e1246ec833bf39b029f | roiei/algo | /leet_code/1738. Find Kth Largest XOR Coordinate Value.py | 1,160 | 3.5 | 4 | import time
from util.util_list import *
from util.util_tree import *
import copy
import collections
from functools import lru_cache
import functools
from typing import List
class Solution:
def kthLargestValue(self, matrix: List[List[int]], k: int) -> int:
rows = len(matrix)
cols = len(matrix[0])
xors = [[0]*cols for _ in range(rows)]
for y in range(rows):
for x in range(cols):
xor = matrix[y][x]
if y > 0:
xor ^= xors[y - 1][x]
if x > 0:
xor ^= xors[y][x - 1]
if y > 0 and x > 0:
xor ^= xors[y - 1][x - 1]
xors[y][x] = xor
vals = []
for line in xors:
vals += line
vals.sort(reverse=True)
print(vals)
return vals[k - 1]
stime = time.time()
print(7 == Solution().kthLargestValue(matrix = [[5,2],[1,6]], k = 1))
print(5 == Solution().kthLargestValue(matrix = [[5,2],[1,6]], k = 2))
print(4 == Solution().kthLargestValue(matrix = [[5,2],[1,6]], k = 3))
print('elapse time: {} sec'.format(time.time() - stime)) |
9c70eb920e41b454ecd5988d0d25421139621e1e | zhanglei13/522 | /leetcode/2014.12.29/Search Insert Position/lusiyu.py | 501 | 3.8125 | 4 | class Solution:
# @param A, a list of integers
# @param target, an integer to be inserted
# @return integer
def searchInsert(self, A, target):
l, r = 0, len(A)-1
while l <= r:
mid = l + r >> 1
if A[mid] == target:
return mid
elif A[mid] > target:
r -= 1
else:
l += 1
return l
A, target = [1, 3, 5, 6], 7
solution = Solution()
print solution.searchInsert(A, target)
|
c357b1ba818ba5e342a30d5a499a4964c82de0cd | jimmygns/ai | /p3/solutions/p5_ordering.py | 2,172 | 3.890625 | 4 | # -*- coding: utf-8 -*-
import operator
def select_unassigned_variable(csp):
"""Selects the next unassigned variable, or None if there is no more unassigned variables
(i.e. the assignment is complete).
This method implements the minimum-remaining-values (MRV) and degree heuristic. That is,
the variable with the smallest number of values left in its available domain. If MRV ties,
then it picks the variable that is involved in the largest number of constraints on other
unassigned variables.
"""
# TODO implement this
min=float("infinity")
for variable in csp.variables:
if variable.is_assigned()==False:
count=len(variable.domain)
if count==min:
num1=0
num2=0
for num in csp.constraints:
if num.var1==variable and num.var2==False or num.var1==False and num.var2==variable:
num1=num1+1
for num in csp.constraints:
if num.var1==minVar and num.var2==False or num.var1==False and num.var2==minVar:
num2=num2+1
if num1>=num2:
minVar=variable
elif count<min:
min=count
minVar=variable
return minVar
def order_domain_values(csp, variable):
"""Returns a list of (ordered) domain values for the given variable.
This method implements the least-constraining-value (LCV) heuristic; that is, the value
that rules out the fewest choices for the neighboring variables in the constraint graph
are placed before others.
"""
# TODO implement this
list=[]
for x in variable.domain:
num=0
for neighbor in csp.constraints[variable]:
for neighbourVar in neighbor.var2.domain:
if neighbor.is_satisfied(x,neighbourVar):
num=num+1
list.append((x,num))
list=sorted(list,key=operator.itemgetter(1),reverse=True)
newList=[]
for value in list:
newList.append(value[0])
return newList
|
13cbb3c72ecdb72e46d024f0f2ebe4102e2f8766 | developer579/Practice | /Python/Python Lesson/Second/Lesson13/Sample1.py | 725 | 3.859375 | 4 | from sklearn import datasets
from sklearn import linear_model
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(0)
x,y = datasets.make_regression(n_samples=100,n_features=1,noise=30)
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=30)
e = linear_model.LinearRegression()
e.fit(x_train,y_train)
y_pred = e.predict(x_test)
print("学習データによる決定係数は",e.score(x_train,y_train),"です。")
print("テストデータによる決定係数は",e.score(x_test,y_test),"です。")
plt.scatter(x_train,y_train,label="train")
plt.scatter(x_test,y_test,label="test")
plt.plot(x_test,y_pred,color="m")
plt.legend()
plt.show() |
13baa027d865d4dd224347e1fe732feb96a4eb61 | jbrewer98/LeetCode | /ZigZagConversion.py | 1,216 | 4.0625 | 4 | # Created by Jack Brewer August 2019
# Description
# Convert a string into zigag format with a given number of rows
# Example: The string "PAYPALISHIRING" is written in a zigzag pattern on 3 rows like this:
# P A H N
# A P L S I I G
# Y I R
# And then read line by line: "PAHNAPLSIIGYIR"
# Strategy
# Need to build string row by row. The first and last row have constant
# distance between each index, while the interior rows vary based on the current row
# Only requires one traversal, and storage for the returned zigzag string
class Solution:
def convert(self, s: str, numRows: int) -> str:
word = ""
counter = 0
if(numRows == 1):
return s
for row in range(numRows):
counter = row
while(counter < len(s)):
word += s[counter]
if(row == 0 or row == numRows - 1):
counter += (numRows * 2) - 2
else:
if(counter + (numRows*2) - 2 - (row * 2) < len(s)):
word+= s[counter + ((numRows*2) - 2) - (row * 2)]
counter += (numRows * 2) - 2
return word
|
a9558c304069320576935ad4aa057a9ba9583c8f | alexpradap/python_coursera | /Semana 1/python_m1/consola_calculo_calorias_reposo.py | 745 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: alexander prada perez
"""
import calculadora_indices as calc
print("Esta funcion calcula la tasa metabolica basal\n")
nombre = input("Por favor escriba su nombre: ")
peso = input("Ingrese su peso en Kilogramos: ")
altura = input("Ingrese su estatura en Metros: ")
edad = input("Ingrese su edad en años: ")
genero = input("Ingrese M para Masculino o F para Femenino: ")
if genero == "M":
genero = 5
else:
if genero == "F":
genero = -161
else:
print("Genero incorrecto, se realizara el calculo con M")
genero = 5
tmb = calc.calcular_calorias_en_reposo(nombre, int(peso), float(altura), int(edad), genero)
print("Su consumo calorico en reposo es: " + str(tmb)) |
09f4fc47a1405549866b22fa980293cac8b1fbc0 | sanpadhy/GITSOURCE | /src/Datastructure/String/DC181_INC/solution.py | 684 | 4.0625 | 4 | # Given a string, split it into as few strings as possible such that each string is a palindrome.
# For example, given the input string "racecarannakayak", return ["racecar", "anna", "kayak"].
# Given the input string "abc", return ["a", "b", "c"].
def splitStringIntoPalindrom(s):
palindroms = list()
i = 0
while i < len(s):
firstChar = s[i]
print(firstChar)
for i, c in enumerate(s[1:]):
if c == firstChar:
palindroms.append(s[:i]+c)
i = i+1
print(palindroms)
print(i)
break
s = "racecarannakayak"
print(splitStringIntoPalindrom(s))
|
b7cb563c8ab333c61e13ec6027910fd177109466 | prai05/ProFun | /Assignment 5/Assignment 5.3.py | 1,374 | 4.40625 | 4 | # Assignment 5
# 010123102 Computer Programming Fundamental
#
# Assignment 5.3
# Write a function list intersection that takes two lists as parameters. Return a list that gives the
# intersection of the two lists- i.e, a list of elements that are common to both lists. Run the following test
# cases and make sure your results are the same (note: the ordering of your outputs does not matter -
# [3,2] is the same as [2,3]):
#
# Phattharanat Khunakornophat
# ID 5901012610091
# SEP 26 2016
# Due Date SEP. 27 2016
# Function for intersec two list
def list_intersection(list_a, list_b):
print('\nlist_A = ', list_a)
print('list_B = ', list_b)
intersecAB = []
for i in list_a:
if i in list_b and i not in intersecAB :
intersecAB.append(i)
return(intersecAB)
# Test case
print(list_intersection([1, 3, 5], [5, 3, 1]))
print(list_intersection([1, 3, 6, 9], [10, 14, 3, 72, 9]))
print(list_intersection([2, 3], [3, 3, 3, 2, 10]))
print(list_intersection([2, 4, 6], [1, 3, 5]))
print('\n')
# Input two list
list_a = []
cnt = int(input('How many element in list_A: ')) # Ask for how many element
for i in range(cnt):
x = int(input('Enter Number: '))
list_a.append(x)
list_b = []
cnt = int(input('\nHow many element in list_B: ')) # Ask for how many element
for i in range(cnt):
x = int(input('Enter Number: '))
list_b.append(x)
print(list_intersection(list_a, list_b))
|
ba3eee0f047f68fd92cd904e0364759efd6f6b4d | ksharonkamal/pythonProject1 | /get_set_string.py | 262 | 3.875 | 4 | class string:
str=""
def get_string(self):
string.str=input("Enter String:")
# print(string.str.upper())
def print_string(self):
str1=string.str.upper()
print(str1)
obj=string()
obj.get_string()
obj.print_string()
|
81f24af4b58613e312fbe227759d5b633bcfe121 | GenericMappingTools/pygmt | /examples/gallery/images/grdgradient.py | 1,842 | 3.609375 | 4 | """
Calculating grid gradient and radiance
--------------------------------------
The :func:`pygmt.grdgradient` function calculates the gradient of a grid file.
In the example shown below we will see how to calculate a hillshade map based
on a Data Elevation Model (DEM). As input :func:`pygmt.grdgradient` gets
a :class:`xarray.DataArray` object or a path string to a grid file, calculates
the respective gradient and returns it as an :class:`xarray.DataArray` object.
We will use the ``radiance`` parameter in order to set the illumination source
direction and altitude.
"""
import pygmt
# Define region of interest around Yosemite valley
region = [-119.825, -119.4, 37.6, 37.825]
# Load sample grid (3 arc-seconds global relief) in target area
grid = pygmt.datasets.load_earth_relief(resolution="03s", region=region)
# calculate the reflection of a light source projecting from west to east
# (azimuth of 270 degrees) and at a latitude of 30 degrees from the horizon
dgrid = pygmt.grdgradient(grid=grid, radiance=[270, 30])
fig = pygmt.Figure()
# define figure configuration
pygmt.config(FORMAT_GEO_MAP="ddd.x", MAP_FRAME_TYPE="plain")
# --------------- plotting the original Data Elevation Model -----------
pygmt.makecpt(cmap="gray", series=[200, 4000, 10])
fig.grdimage(
grid=grid,
projection="M12c",
frame=["WSrt+tOriginal Data Elevation Model", "xa0.1", "ya0.1"],
cmap=True,
)
fig.colorbar(position="JML+o1.4c/0c+w7c/0.5c", frame=["xa1000f500+lElevation", "y+lm"])
# --------------- plotting the hillshade map -----------
# Shift plot origin of the second map by 12.5 cm in x direction
fig.shift_origin(xshift="12.5c")
pygmt.makecpt(cmap="gray", series=[-1.5, 0.3, 0.01])
fig.grdimage(
grid=dgrid,
projection="M12c",
frame=["lSEt+tHillshade Map", "xa0.1", "ya0.1"],
cmap=True,
)
fig.show()
|
029feec40ff3a6d1a29c8adcdeb4eb1be3e36658 | daniel-reich/ubiquitous-fiesta | /pEozhEet5c8aFJdso_10.py | 349 | 3.53125 | 4 |
def all_about_strings(txt):
result = [len(txt), txt[0], txt[-1], txt[(len(txt)-1)//2:(len(txt)+2)//2]]
i = txt.find(txt[1])
j = txt.find(txt[1], i+1)
if j == -1:
result.append('not found')
if j != 0:
result.append('@ index ' + str(j))
if result[-1] == '@ index -1':
result.pop(-1)
return result
|
34a14ad69d3a1ed742dc8f5c43fc1b274434b061 | Rohit-Gupta-Web3/Articles | /ML Libariries/python_matplotlib/scatter_2d.py | 489 | 4 | 4 | import matplotlib.pyplot as plt
# x-axis values
x = [2,4,5,7,6,8,9,11,12,12]
# y-axis values
y = [1,2,3,4,5,6,7,8,9,10]
# plotting points as a scatter plot
plt.scatter(x, y, label= "stars", color= "green",
marker= "x", s=30)
# x-axis label
plt.xlabel('x - axis')
# frequency label
plt.ylabel('y - axis')
# plot title
plt.title('Scatter plot!')
# showing legend
plt.legend()
# function to show the plot
plt.show()
|
7cb17a29ffd77abdd6b38388b244de3e51cf0cdb | lulzzz/tflearn_seq2seq | /pattern.py | 1,690 | 4.0625 | 4 | '''
Define pattern of integers for seq2seq example.
'''
import numpy as np
class SequencePattern(object):
INPUT_SEQUENCE_LENGTH = 10
OUTPUT_SEQUENCE_LENGTH = 10
INPUT_MAX_INT = 9
OUTPUT_MAX_INT = 9
PATTERN_NAME = "sorted"
def __init__(self, name=None, in_seq_len=None, out_seq_len=None):
if name is not None:
assert hasattr(self, "%s_sequence" % name)
self.PATTERN_NAME = name
if in_seq_len:
self.INPUT_SEQUENCE_LENGTH = in_seq_len
if out_seq_len:
self.OUTPUT_SEQUENCE_LENGTH = out_seq_len
def generate_output_sequence(self, x):
'''
For a given input sequence, generate the output sequence. x is a 1D numpy array
of integers, with length INPUT_SEQUENCE_LENGTH.
Returns a 1D numpy array of length OUTPUT_SEQUENCE_LENGTH
This procedure defines the pattern which the seq2seq RNN will be trained to find.
'''
return getattr(self, "%s_sequence" % self.PATTERN_NAME)(x)
def maxmin_dup_sequence(self, x):
'''
Generate sequence with [max, min, rest of original entries]
'''
x = np.array(x)
y = [ x.max(), x.min()] + list(x[2:])
return np.array(y)[:self.OUTPUT_SEQUENCE_LENGTH] # truncate at out seq len
def sorted_sequence(self, x):
'''
Generate sorted version of original sequence
'''
return np.array( sorted(x) )[:self.OUTPUT_SEQUENCE_LENGTH]
def reversed_sequence(self, x):
'''
Generate reversed version of original sequence
'''
return np.array( x[::-1] )[:self.OUTPUT_SEQUENCE_LENGTH]
|
bc6d399be6b53dbf094dbc2de349b2f5f32ce865 | aa88bb/Introduction-to-programming-using-python | /chapter4.py | 346 | 3.890625 | 4 | import random
print(random.randint(0,2))
print(random.randrange(0,3))
print(random.random())
# year = eval(input("enter a year:"))
# isLeapYear = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
# print(isLeapYear)
count = 0
while count < 4:
print("programming is fun.",count)
count += 1
for i in range(2,9,3):
print(i)
|
429ae3d10ee8a89d9dede6d5de6e62c41d6b5e1b | nishanthegde/bitesofpy | /63/traffic.py | 967 | 3.828125 | 4 | from collections import namedtuple
from itertools import cycle, islice
from time import sleep
State = namedtuple('State', 'color command timeout')
def traffic_light():
"""Returns an itertools.cycle iterator that
when iterated over returns State namedtuples
as shown in the Bite's description"""
color = ['red', 'green', 'amber']
command = ['Stop', 'Go', 'Caution']
timeout = [2, 2, 0.5]
states_zipped = list(zip(color, command, timeout))
states = [State(s[0], s[1], s[2]) for s in states_zipped]
return cycle(states)
if __name__ == '__main__':
print('thank you for everything...')
# print a sample of 10 states if run as standalone program
# for state in islice(traffic_light(), 10):
# print(f'{state.command}! The light is {state.color}')
# sleep(state.timeout)
it = traffic_light()
print(list(islice(it, 96)))
print(list(islice(it, 100, 217)))
|
c2e7631712868d6e7f6ef10ecbe8c11cea70740a | sardort96/Diffie-Hellman-Public-Key-Exchange | /diffieHellman.py | 2,155 | 3.84375 | 4 | import string
plaintext = input('Enter the message you want to encrypt: ')
plaintext = plaintext.replace(' ', '')
plaintext = plaintext.upper()
plaintext = list(plaintext)
sharedPrime = int(input('Enter a large prime number to share: '))
if sharedPrime > 1:
for i in range(2, sharedPrime):
if (sharedPrime % i) == 0:
print(sharedPrime, 'is not a prime number')
break
print('Publicly shared prime is ', sharedPrime)
else:
print(sharedPrime, 'is not a prime number')
exit()
sharedGenerator = int(input('Enter a shared generator less than ' + str(sharedPrime) + ': ' ))
if sharedGenerator < sharedPrime:
print('Publicly shared generator is ', sharedGenerator)
else:
print(sharedGenerator, 'is larger than' + sharedPrime)
exit()
secretA = int(input('Enter a secret key for person A: '))
secretB = int(input('Enter a secret key for person B: '))
# Person A sends person B = g^a mod p
A = (sharedGenerator**secretA) % sharedPrime
print('Person A sends over public channel: ', A)
# Person B sends person A = g^b mod p
B = (sharedGenerator ** secretB) % sharedPrime
print('Person B sends over public channel: ', B)
print('Privately calculated key: ')
# Person A computes: s = B^a mod p
sharedSecretA = (B ** secretA) % sharedPrime
print('Person A\'s Shared Secret: ', sharedSecretA)
# Person B computes: s = A^b mod p
sharedSecretB = (A ** secretB) % sharedPrime
print('Person B\'s Shared Secret: ', sharedSecretB)
print('\n``````````The Key has been chosen```````````\n')
letters = list(string.ascii_uppercase)
numbers = list()
for i in range(0,26):
numbers.append(i)
dictionary = dict(zip(letters, numbers))
plainDictionary = {}
for key, val in dictionary.items():
for i in plaintext:
if i == key:
plainDictionary[i] = val
ciphertextVals = list()
for i in plaintext:
for key, val in dictionary.items():
if i == key:
y = (val + sharedSecretA) % 26
ciphertextVals.append(y)
ciphertext = ''
for i in ciphertextVals:
for key, val in dictionary.items():
if i == val:
ciphertext = ciphertext + key
print('Ciphertext: ', ciphertext) |
cbac3a50a2262ac947030f357eaeeb7d5f112a0c | mirkomantovani/UncommonHacks-MemeSearch | /preprocess.py | 1,173 | 3.984375 | 4 | # Mirko Mantovani
import re
import string
from nltk.stem import PorterStemmer
# removing digits and returning the word
def replace_digits(st):
return re.sub('\d', '', st)
# returns true if the word has less or equal 2 letters
def lesseq_two_letters(word):
return len(word) <= 2
STOP_WORDS_PATH = "./stopwords.txt"
with open(STOP_WORDS_PATH, "r") as stop_file:
stop_words = stop_file.readlines()
stop_words = list(map(lambda x: x[:-1], stop_words))
ps = PorterStemmer()
def stem(word):
return ps.stem(word)
def preprocess(doc):
# Splitting on whitespaces
doc = doc.split()
# Converting all words to lowercase
doc = [x.lower() for x in doc]
# Stop word elimination
doc = [s for s in doc if s not in stop_words]
# Porter Stemmer
doc = list(map(stem, doc))
# Applying stop word elimination again
doc = [s for s in doc if s not in stop_words]
# Removing punctuations in words
doc = [''.join(c for c in s if c not in string.punctuation) for s in doc]
# Replace numbers with empty string
doc = map(replace_digits, doc)
# Removing empty words
doc = [s for s in doc if s]
return doc
|
01f3d03979b4eaf7d01b3c84699f73ffe7c13319 | studentjnguyen/myprojects | /Section 4 Exercise Project.py | 477 | 4.34375 | 4 | """
This is a rest style.
If input is divisible by 3, it prints fizz
If input is divisible by 5, it prints buzz
If input is divisible by both 3 and 5, it prints FizzBuzz
Anything else is returned
"""
def fizz_buzz(input):
fizz = input % 3
buzz = input % 5
if fizz == 0 and buzz == 0:
print("FizzBuzz")
elif fizz == 0:
print("Fizz")
elif buzz == 0:
print("Buzz")
else:
print(input)
fizz_buzz(5)
|
5921b9e0783943cd3b4047f5eff915d57e760656 | pu-bioinformatics/python-exercises-LandiMi2 | /Scripts/NoteBook06.py | 1,627 | 4.1875 | 4 | #! /home/cofia/miniconda3/bin/python
#Question - Write a function percentageGC that calculates the GC content of a DNA sequence
# - The function should return the %GC content
# - The Function should return a message if the provided sequence is not DNA (This should be checked by a different function, called by your function)
#input sequence data mydna, yourdna and testdna
mydna = "CAGTGATGATGACGAT"
yourdna = "ACGATCGAGACGTAGTA"
testdna = "ATFRACGATTGHAHYAK"
#create a function that returns the percentage GC content form mydna and yourdna sequence data
def percent_GC(seq): ## Should firt test if the seqence is avalid DNA seq -2
gc_count = seq.count('G') + seq.count('C')
return 100 * (gc_count/len(seq))
#Define what makes a DNA strand
proper_DNA="ATGC"
#create a function that returns whether sequence data is a DNA data set
def valid(sequence):
for base in sequence:
if base not in proper_DNA:
return "This is Not DNA sequence" ##CK: This function should be called by the percent_GC -1
# so the return should be True or False
return "This is DNA sequence"
#creating a variable calling the function created to enable printing the results
testdna1 = valid(testdna)
mydna1=percent_GC(mydna)
yourdna1=percent_GC(yourdna)
#print out results of percentage GC content and if sequence is DNA or not
print ('Here is the percentage GC content of mydna sequence:%.2f' %mydna1)
print ('Here is the percentage GC content of yourdna sequence sequence:%.2f' %yourdna1)
print ('Checking if testdna sequence is DNA: %s' %testdna1)
|
ca47efef3c0309c33c25db8967bf9185793adac0 | muzhen321/FPIR17 | /pir_h1.py | 2,920 | 3.53125 | 4 | #! /usr/bin/python
# -*- coding: utf-8 -*-
"""Rank sentences based on cosine similarity and a query."""
from argparse import ArgumentParser
from collections import Counter
import numpy as np
def get_sentences(file_path):
"""Return a list of sentences from a file."""
with open(file_path, encoding='utf-8') as hfile:
return hfile.read().splitlines()
def get_top_k_words(sentences, k):
"""Return the k most frequent words as a list."""
words = []
for sentence in sentences:
words.extend(sentence.split())
#调用了库文件 Counter
return [word for word, _ in Counter(words).most_common(k)]
def encode(sentence, vocabulary):
"""Return a vector encoding the sentence."""
words = Counter(sentence.split())
vector = [words.get(token, 0) for token in vocabulary]
return np.asarray(vector)
def get_top_l_sentences(sentences, query, vocabulary, l):
"""
For every sentence in "sentences", calculate the similarity to the query.
Sort the sentences by their similarities to the query.
Return the top-l most similar sentences as a list of tuples of the form
(similarity, sentence).
"""
encoded_query = encode(query, vocabulary)
similarities = []
for sentence in sentences:
encoded_sentence = encode(sentence, vocabulary)
sim = cosine_sim(encoded_sentence, encoded_query)
similarities.append((sim, sentence))
# sort by similarities, descending, and keep the top-l ones
return sorted(similarities, key=lambda x: x[0], reverse=True)[:l]
def cosine_sim(u, v):
"""Return the cosine similarity of u and v."""
return np.dot(u, v) / np.linalg.norm(u) / np.linalg.norm(v)
def main():
arg_parser = ArgumentParser()
arg_parser.add_argument('INPUT_FILE', help='An input file containing sentences, one per line')
arg_parser.add_argument('QUERY', help='The query sentence')
arg_parser.add_argument('-k', type=int, default=1000,
help='How many of the most frequent words to consider')
arg_parser.add_argument('-l', type=int, default=10, help='How many sentences to return')
args = arg_parser.parse_args()
sentences = get_sentences(args.INPUT_FILE)
top_k_words = get_top_k_words(sentences, args.k)
query = args.QUERY.lower()
print('using vocabulary: {}\n'.format(top_k_words))
print('using query: {}\n'.format(query))
# suppress numpy's "divide by 0" warning.
# this is fine since we consider a zero-vector to be dissimilar to other vectors
with np.errstate(invalid='ignore'):
result = get_top_l_sentences(sentences, query, top_k_words, args.l)
print('result:')
for sim, sentence in result:
print('{:.5f}\t{}'.format(sim, sentence))
if __name__ == '__main__':
main()
|
692988082f2b17832f6149c9479133ddfa3872d1 | jobfb/Python_introdution | /crescente.py | 762 | 4.0625 | 4 | #leia uma quantidade indeterminada de duplas de valores inteiros X e Y.
# Escreva para cada X e Y uma mensagem que indique se esses valores foram digitados em ordema crescente ou decrescente
# O programa deve finalizar quando os dois valores forem iguais.
X = int
Y = int
X = int(input("digite um valor:"))
Y = int(input("digite outro valor :"))
while X!= Y:
if X>Y:
print("Os valores foram digitados em ordem crescente")
else:
print("Os valores foram digitados em ordem decrescente")
print("caso queira continuar insira novos valores, para cancelar a repetição insira o mesmo valor em ambos espaços")
X = int(input("digite um valor:"))
Y = int(input("digite outro valor :"))
print("fim ") |
8a124a3d55850c632b737412f479510d3ac0a975 | umarpatel23/umar_patel_repository | /DiffEqYPredictor.py | 524 | 3.53125 | 4 | import numpy as np
import matplotlib.pyplot as plt
'''intitial condition'''
y_initial = 3
def get_dy_dt(current_y_value):
return 1.01 - current_y_value - (0.01 * (current_y_value**4))
num_of_intervals = 11
time = np.linspace(0, 2, num=num_of_intervals)
time_interval = time[1] - time[0]
y_value = np.zeros(num_of_intervals)
y_value[0] = y_initial
for i in range (1, num_of_intervals):
y_value[i] = y_value[i-1] + (get_dy_dt(y_value[i-1]) * time_interval)
print(y_value[10])
plt.plot(time, y_value)
plt.show() |
e6689529c707c156abd39081f630c6d123dbdf9b | sarthikg/python-data-structures | /Queue.py | 1,145 | 3.796875 | 4 | class Node():
def __init__(self, value):
self.value = value
self.next = None
class Queue():
def __init__(self):
self.first = None
self.last = None
self.size = 0
def __repr__(self):
if self.size > 0:
currentNode = self.first
outputString = ''
for i in range(0, self.size):
outputString += str(currentNode.value) + ' --> '
currentNode = currentNode.next
return str(self.first.value) + ' | ' + str(self.last.value) + ' | ' + str(self.size) + ' | ' + outputString
else:
return '## | ## | 0 | '
def enqueue(self, value):
newNode = Node(value)
if self.size == 0:
self.first = newNode
self.last = newNode
else:
self.last.next = newNode
self.last = newNode
self.size += 1
def dequeue(self):
if self.size == 0:
return None
elif self.size == 1:
currentNode = self.first
currentNode.next = None
self.first = None
self.last = None
else:
currentNode = self.first
self.first = currentNode.next
currentNode.next = None
self.size -= 1
return currentNode.value |
d69d60423a6692948775e2fe20957e3cb78f0c6c | pylux/firstrep | /try.py | 114 | 3.890625 | 4 | #!/usr/bin/python3
while 1:
for x in range(1,50):
print(str(x).rjust(2),str(x*x).rjust(3),str(x*x*x).rjust(5))
|
52d12c8cfc7d011f93d211c9fb8e7e0098ef9e23 | 953250587/leetcode-python | /VerifyPreorderSerializationOfABinaryTree_MID_331.py | 2,336 | 4.0625 | 4 | """
One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as #.
_9_
/ \
3 2
/ \ / \
4 1 # 6
/ \ / \ / \
# # # # # #
For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#", where # represents a null node.
Given a string of comma separated values, verify whether it is a correct preorder traversal serialization of a binary tree. Find an algorithm without reconstructing the tree.
Each comma separated value in the string must be either an integer or a character '#' representing null pointer.
You may assume that the input format is always valid, for example it could never contain two consecutive commas such as "1,,3".
Example 1:
"9,3,4,#,#,1,#,#,2,#,6,#,#"
Return true
Example 2:
"1,#"
Return false
Example 3:
"9,#,#,1"
Return false
"""
class Solution(object):
def isValidSerialization(self, preorder):
"""
:type preorder: str
:rtype: bool
39ms
"""
prepare=[]
preorder=preorder.split(',')
for i in preorder[::-1]:
if i=='#':
prepare.append(i)
else:
if len(prepare)>=2:
prepare.pop()
else:
return False
if len(prepare)>1:
return False
return True
def isValidSerialization(self, preorder):
"""
:type preorder: str
:rtype: bool
36ms
"""
# remember how many empty slots we have
# non-null nodes occupy one slot but create two new slots
# null nodes occupy one slot
p = preorder.split(',')
# initially we have one empty slot to put the root in it
slot = 1
for node in p:
# no empty slot to put the current node
if slot == 0:
return False
# a null node?
if node == '#':
# ocuppy slot
slot -= 1
else:
# create new slot
slot += 1
# we don't allow empty slots at the end
return slot == 0
print(Solution().isValidSerialization("9,3,4,#,#,1,#,#,2,#,6,#,#"))
|
36d03609f6311b0b899d6ef5a878eaef59fce265 | johnehunt/PythonDataScienceIntro | /07-grouping-and-combining/concatenation_exampes.py | 620 | 3.515625 | 4 | import pandas as pd
df1 = pd.DataFrame([[56, 76],
[75, 68],
[67, 64]],
index=['John', 'Denise', 'Adam'],
columns=['English', 'Maths'])
df2 = pd.DataFrame([[62, 37],
[75, 89]],
index=['John', 'Adam'],
columns=['Physics', 'Chemistry'])
print(df1)
print('.' * 25)
print(df2)
print('-' * 25)
combined_df = pd.concat([df1, df2], axis='columns')
print(combined_df)
print('-' * 25)
combined_df = pd.concat([df1, df2], axis='columns', keys=['semester1', 'semester2'])
print(combined_df)
|
8d5212c8445302ef33118b9c9b9f9ae80bab28cb | coraallensavietta/pythonExercises | /PS4/isValidWord.py | 2,669 | 3.90625 | 4 | WORDLIST_FILENAME = "H:/PS4/words.txt"
def loadWords():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# wordList: list of strings
wordList = []
for line in inFile:
wordList.append(line.strip().lower())
print " ", len(wordList), "words loaded."
return wordList
def getFrequencyDict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
return: dictionary
"""
# freqs: dictionary (element_type -> int)
freq = {}
for x in sequence:
freq[x] = freq.get(x,0) + 1
return freq
def isValidWord(word, hand, wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: dictionary (string -> int)
wordList: list of lowercase strings
"""
newHand = hand.copy()
wordDict = getFrequencyDict(word)
if (word in wordList and len(word) > 0):
try:
for key in wordDict:
if wordDict[key] > newHand[key]:
return False
break
return True
except KeyError:
return False
else:
return False
#try:
# if word in wordList:
# for key in wordDict:
# for key in range(wordDict[key]):
# if newHand[key] > 0:
# newHand[key] -= 1
# print newHand
# else:
# print False
# break
# return True
# else:
# return False
#except KeyError:
# return False
#if word in wordList:
#
# for l in word:
# if l in newHand.keys():
# print True
# if newHand[l] > 0:
# newHand[l] -= 1
# else:
# print False
#else:
# print False
#else:
# print False
#else:
# False
#newHand = hand.copy()
#for l in word:
# newHand[l] -= 1
#return newHand |
3d7afe8d73df510fe8156656d6d2cb11e4bad23d | andyyvo/CS111 | /PS 2/ps2pr1.py | 2,267 | 4.34375 | 4 | #
# ps2pr1.py - Problem Set 2, Problem 1
#
# Functions with numeric inputs
#
# If you worked with a partner, put their contact info below:
# partner's name:
# partner's email:
#
# function 0
def opposite(x):
""" returns the opposite of its input
input x: any number (int or float)
"""
return -1*x
# put your definitions for the remaining functions below
# function 1
def cube(x):
""" returns the cube of its input
input x: any number (int or float)
"""
return x**3
# function 2
def convert_to_inches(yards,feet):
""" returns the conversion of inches of two numeric inputs that together represent a single length broken up into yards and feet
input yards and feet: any number (int or float)
"""
if yards < 0:
yards = 0
if feet < 0:
feet = 0
a = 36 * yards
b = 12 * feet
return a+b
# function 3
def area_sq_inches(height_yds, height_ft, width_yds, width_ft):
""" returns the area of a rectangle in square inches by determining height and width of rectangle in inches, then returning the product of those two values
input height_yds, height_ft, width_yds, width_ft: any number (int or float)
"""
if height_yds < 0:
height_yds = 0
if height_ft < 0:
height_ft = 0
if width_yds < 0:
width_yds = 0
if width_ft < 0:
width_ft = 0
a = 36 * height_yds
b = 12 * height_ft
c = 36 * width_yds
d = 12 * width_ft
height_in = a + b
width_in = c + d
return height_in * width_in
# function 4
def median(a,b,c):
""" returns the median of the three inputs (the value that falls in the middle of the other two when the three values are listed in increasing order)
input a,b,c: any number (int or float)
"""
if b <= a <= c:
return a
elif c <= a <= b:
return a
elif a <= b <= c:
return b
elif c <= b <= a:
return b
elif a <= c <= b:
return c
elif b <= c <= a:
return c
# test function with a sample test call for function 0
def test():
""" performs test calls on the functions above """
print('opposite(-8) returns', opposite(-8))
# optional but encouraged: add test calls for your functions below
|
b14f3d5d32fa175d2a2e9476beb1d5d4065ebbb6 | Moustafa-Eid/Python-Programs | /Unit 3/Assignment/Testing/EidLoopQ1.py | 3,145 | 4.125 | 4 | # Name: Moustafa Eid
# Date: May 8 2017
# Class: ICS3U1-03
# Description: Repetition Assignment - Calculate Lean , Fat and Jack Sprat Numbers
# Function That checks if a number is Lean
def isLean(n, t):
if t == n + 1:
return True
else:
return False
# Function That checks if a number is Fat
def isFat(n, t):
if t > 3*n:
return True
else:
return False
# Function That checks if a number is Jack Sprat
def isJackSprat(n, t, t2):
if t == n+1 and t2 > 3*(n+1):
return True
else:
return False
# Input for number that will be checked
num = int(input("Please enter a number: "))
# Declaring the accumulator variables
total = 0
total2 = 0
total3 = 0
total4 = 0
# Creating a list to store the Jack Sprat Numbers
isSprat = []
# Loop that checks if a number is Lean
for factor in range(1,num+1):
if num % factor == 0:
total += factor
# Loop that checks if a number is Fat
for factor in range(1,num+2):
if (num+1) % factor == 0:
total2 += factor
# If statements that checks if the number is Lean and prints it out
if isLean(num,total) == True:
print ("Lean: Yes")
elif isLean(num,total) == False:
print ("Lean: No")
# If statements that checks if the number is Fat and prints it out
if isFat(num,total) == True:
print ("Fat: Yes")
elif isFat(num,total) == False:
print ("Fat: No")
# If statements that checks if the number is Jack Sprat and prints it out
if isJackSprat(num, total, total2) == True:
print ("Jack Sprat: Yes")
elif isJackSprat(num, total, total2) == False:
print ("Jack Sprat: No")
# Prints Text before Jack Sprat Numbers
print ("These are the Jack Sprat Numbers from 1 - 10000")
# Loop That counts all the Jack Sprat numbers from 1-10000
for count in range (2,10001):
if count != 1: # Exception to make program more efficient
if count % 2 != 0: # Exception to make program more efficient
if count % 3 != 0: # Exception to make program more efficient
if count % 5 != 0: # Exception to make program more efficient
if count % 7 != 0: # Exception to make program more efficient
isPrime = True #Checks if count is prime
for factor in range(2,int(count**0.5) + 1):
if count % factor == 0:
isPrime = False # If count is not prime it breaks loop
break
for factor in range (2,count+2): # Checks if number is Fat
if (count+1) % factor == 0:
total4 += factor # Accumulates Factors for Fat Numbers
if isPrime and total4 > 3*(count + 1):
isSprat.append(count) # Append that adds all the Jack Sprat Numbers calculated to the list
# Resetting variable back to 0 for the while loop to restart
total3 = 0
total4 = 0
# Prints All the Jack Sprat Numbers in the list
print (isSprat) |
b7c3f4891b573f7e26e710e8ba3a16e4f81edc35 | zihuaweng/leetcode-solutions | /leetcode_python/266.Palindrome_Permutation.py | 436 | 3.796875 | 4 | #!/usr/bin/env python3
# coding: utf-8
# Time complexity: O()
# Space complexity: O()
# https://leetcode.com/problems/palindrome-permutation/
class Solution:
def canPermutePalindrome(self, s: str) -> bool:
counter = collections.Counter(s)
match = 0
for c in counter.values():
if c & 1 == 1:
match += 1
if match > 1:
return False
return True |
b999937ef8fa39d138c6edeba73aa0528d0530f5 | FishRedLeaf/my_code | /jianzhi_offer/25复杂链表的复制.py | 1,904 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 21 20:03:23 2019
@author: 鱼红叶
输入一个复杂链表
(每个节点中有节点值,以及两个指针,一个指向下一个节点,
另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。
(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
"""
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# write code here
if pHead == None:
return None
self.cloneNodes(pHead)
self.ConnectRandomNodes(pHead)
return self.reconstructNodes(pHead)
def cloneNodes(self, pHead):
pNode = pHead
while pNode:
tmp = RandomListNode(pNode.label)
tmp.next = pNode.next
pNode.next = tmp
pNode = tmp.next
def ConnectRandomNodes(self, pHead):
pNode = pHead
while pNode:
pCloned = pNode.next
if pNode.random != None:
pCloned.random = pNode.random.next
pNode = pCloned.next
def reconstructNodes(self, pHead):
pNode = pHead
pClonedHead = pClonedNode = pNode.next
pNode.next = pClonedNode.next
pNode = pNode.next
while pNode:
pClonedNode.next = pNode.next
pClonedNode = pClonedNode.next
pNode.next = pClonedNode.next
pNode = pNode.next
return pClonedHead
|
da96e8238b9e218665b524c2f2111a7c11f970ee | kelvi5/Python | /Variavel.py | 627 | 3.890625 | 4 | nome = 'Kelvin'
idade = 23
flu = 1.2
ver = True
fal = False
print(nome, idade)
print(f'O seu nome é {nome} e você tem {idade} anos')
print('O seu nome é {} e você tem {} anos'.format(nome, idade))
print(type(nome), type(idade), type(flu), type(ver), type(fal), type(True))
str = 'Kelvin pereira da silva'
str = str.upper()
print(str)
str = str.lower()
print(str)
str = str.title()
print(str)
print(len(str))
str = str.replace('Kelvin', 'Kel')
print(str)
print(str.count('l'))
print(str.find('a'))
nome = input(print('Digite o seu nome: '))
idade = input(print('Digite sua idade: '))
print('Olá {} vocé tem {} anos'.format(nome, idade)) |
9184be9ac3e27f6479195abeca702671d557f976 | JayHennessy/PythonPractice | /python_basics_tutorial/SQLite_tutorial.py | 1,161 | 4.53125 | 5 | # SQLite is built into sublime and its good for small databases
import sqlite3
# setup a connection to SQLite. This will automatically create the database employee.db
# Here you could also use ':memory:' to make a database in memory
conn = sqlite3.connect('employee.db')
# create a cursor that allows you to make SQL commands
c = conn.cursor()
# here is the SQL code to execute. The triple brackets is called a doc string, it allows you to make a string across
# multiple lines
# c.execute("""CREATE TABLE employees (
# first text,
# last text,
# pay int
# )""")
#note: after you initially create the database(table) you need to get rid of
# that bit of code, it will throw an error if you try to create the same table
#twice
# play around with the database
#c.execute("INSERT INTO employees VALUES ('Brian', 'Hen', 500)")
#conn.commit()
c.execute("SELECT * FROM employees WHERE last= 'Hen'")
#this gets the next row in results
#print(c.fetchone())
# this gets all the rows in a list
print(c.fetchall())
#this commits the command not the 'c', it is easy to forget
conn.commit()
#make sure to end by closing the connection
conn.close()
|
57abb48e811ba1fae03f610a948bea1d8ce8f99f | Luminiscental/AdventOfCode2019 | /day20.py | 4,645 | 3.796875 | 4 | """AdventOfCode2019 - Day 20"""
import collections
from util import bfs, dijkstra, tuple_add
from day18 import parse
Portal = collections.namedtuple("Portal", "label is_inner")
def flip_portal(portal):
"""Flip from inner to outer portal or vice versa."""
return Portal(label=portal.label, is_inner=not portal.is_inner)
def label_for(fst_letter, snd_letter, direction):
"""Get the label for a portal given the encountered letters and direction."""
# If we went left or up reverse it
return (
f"{snd_letter}{fst_letter}" if -1 in direction else f"{fst_letter}{snd_letter}"
)
def find_portals(maze):
"""Find each inner and outer portal."""
# inner_portals[inner_location] = label
inner_portals = {}
# outer_portals[outer_location] = label
outer_portals = {}
# Look at every point in the maze
for pos, tile in maze.items():
# If it's traversable look at everything adjacent to it
if tile == ".":
for offset in ((1, 0), (0, 1), (-1, 0), (0, -1)):
adj = tuple_add(pos, offset)
adj_tile = maze[adj]
# If it's the start of a label find the whole label
if adj_tile.isupper():
next_pos = tuple_add(adj, offset)
next_tile = maze[next_pos]
assert next_tile.isupper(), "ill-formed label found"
after_pos = tuple_add(next_pos, offset)
label = label_for(adj_tile, next_tile, offset)
if after_pos in maze:
inner_portals[pos] = label
else:
outer_portals[pos] = label
return inner_portals, outer_portals
def find_distances(maze, inner_portals, outer_portals):
"""Calculate the distances between each portal using BFS."""
distances = collections.defaultdict(dict)
def update(pos, dist, state):
if pos in inner_portals:
portal = Portal(label=inner_portals[pos], is_inner=True)
if state != portal:
distances[state][portal] = dist
elif pos in outer_portals:
portal = Portal(label=outer_portals[pos], is_inner=False)
if state != portal:
distances[state][portal] = dist
return state
for inner, label in inner_portals.items():
bfs(
traversable_pred=lambda pos: maze[pos] == ".",
start_node=inner,
state_updater=update,
initial_state=Portal(label, is_inner=True),
)
for outer, label in outer_portals.items():
bfs(
traversable_pred=lambda pos: maze[pos] == ".",
start_node=outer,
state_updater=update,
initial_state=Portal(label, is_inner=False),
)
return distances
def part1(maze, state):
"""Solve for the answer to part 1."""
inner_portals, outer_portals = find_portals(maze)
distances = state["distances"] = find_distances(maze, inner_portals, outer_portals)
start_portal = state["start_portal"] = Portal(label="AA", is_inner=False)
end_portal = state["end_portal"] = Portal(label="ZZ", is_inner=False)
def get_edges(portal):
# Walking edges
yield from distances[portal].items()
# Teleporting edges
if portal.label not in ("AA", "ZZ"):
yield flip_portal(portal), 1
return dijkstra(
nodes=distances.keys(),
edge_producer=get_edges,
start_node=start_portal,
end_node=end_portal,
)
def part2(_, state):
"""Solve for the answer to part 2."""
distances = state["distances"]
start_portal = state["start_portal"]
end_portal = state["end_portal"]
Node = collections.namedtuple("Node", "portal level")
def get_edges(node):
# Walking edges
for portal, dist in distances[node.portal].items():
yield Node(portal, node.level), dist
# Teleporting edges
if node.portal.label not in ("AA", "ZZ"):
if node.portal.is_inner:
yield Node(flip_portal(node.portal), node.level + 1), 1
elif node.level > 0:
yield Node(flip_portal(node.portal), node.level - 1), 1
# Assume the shortest path doesn't go beyond level 50
max_level = 50
return dijkstra(
nodes={
Node(portal, level)
for portal in distances.keys()
for level in range(max_level + 1)
},
edge_producer=get_edges,
start_node=Node(start_portal, level=0),
end_node=Node(end_portal, level=0),
)
|
95f77506adf9f9d697650c7a97739994e2ac00aa | puzzledsean/leetcode | /python/phone_letter_combinations.py | 2,652 | 4.09375 | 4 | # Given a digit string, return all possible letter combinations that the number could represent.
# A mapping of digit to letters (just like on the telephone buttons) is given below.
# Example
# Input:Digit string "23"
# Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
digit_mapping = {'1':'*',
'2': ['a','b','c'],
'3': ['d','e','f'],
'4': ['g','h','i'],
'5': ['j','k','l'],
'6': ['m','n','o'],
'7': ['p','q','r','s'],
'8': ['t','u','v'],
'9': ['w','x','y','z'],
'0': [' ']}
letter_combo = self.generate_letter_combinations(digits, digit_mapping)
return letter_combo
def generate_letter_combinations(self, digits, digit_mapping):
if len(digits) == 0:
return []
if len(digits) == 1:
return digit_mapping[digits[0]]
#base case of 2, generate possibilities for 2 digits
if len(digits) == 2:
list_to_compile = []
first_digit_possibilities = digit_mapping[digits[0]]
second_digit_possibilities = digit_mapping[digits[1]]
for i in range(len(first_digit_possibilities)):
for j in range(len(second_digit_possibilities)):
generated_digit = first_digit_possibilities[i] + second_digit_possibilities[j]
list_to_compile.append(generated_digit)
return list_to_compile
#recursive case, take current first digit and enumerate all of its possible values onto the running digit possibilities list
else:
removed_first_digit = digits[0]
generated_list = self.generate_letter_combinations(digits[1:], digit_mapping)
removed_first_digit_possibilities = digit_mapping[removed_first_digit]
list_to_compile = []
#each digit will basically have a turn to slap on its possibilities to the running digit possibilities list
for i in range(len(removed_first_digit_possibilities)):
for j in range(len(generated_list)):
generated_digit = removed_first_digit_possibilities[i] + generated_list[j]
list_to_compile.append(generated_digit)
return list_to_compile |
eefaae4841b5e7d64ad08487dbe11967ab958c28 | 1019350030wfj/python_demo | /lift/xiamen_lift_fsd.py | 891 | 3.703125 | 4 | '''
使用selenium模拟浏览器
抓取电梯查询结果
'''
# 导入selenium模块中的web引擎
# from selenium import webdriver
#
# # 建立浏览器对象,通过phantom.js
# browser = webdriver.PhantomJS()
#
# url = "http://117.25.179.165:7003/wapq/elevatorSearch.jsp?&EqpCod=T008858"
#
# browser.get(url)
#
# browser.implicitly_wait(3)
#
# button = browser.find_element_by_name("form")
#
# button.submit()
#
# print(browser.page_source)
import requests
head = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36',
'Referer': 'http://117.25.179.165:7003/wapq/elevatorSearch.jsp?&EqpCod=T008859'}
url = 'http://117.25.179.165:7003/wapq/elevator.do?task=search'
data = {
'eqpCod': "T008859",
'smsCod': "",
'regCod': "",
}
loginhtml = requests.post(url, data=data, headers=head)
print(loginhtml)
|
9ca20f5046e635da49d0a51d815a3a2ed2c84807 | KentoDodo/libs | /util/file.py | 867 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
from logger import Logger
def output_csv(csvfile='output.csv', header=[], data=[]):
"""2次元配列`data`を指定ファイル`csvfile`にcsv形式で保存する"""
f = open(csvfile, 'w')
writer = csv.writer(f, lineterminator='\n')
writer.writerow(header)
writer.writerows(data)
f.close()
Logger().info("Output to csv file (%s)" % csvfile)
def input_csv(csvfile='output.csv'):
"""`csvfile`で指定したcsv形式ファイルを読み込む"""
def isfloat(value):
try:
float(value)
return True
except:
return False
f = open(csvfile, 'r')
reader = csv.reader(f)
header = next(reader)
data = [[(float(d) if isfloat(d) else d) for d in row] for row in reader]
f.close()
return header, data
|
0fddfde5b98d17f2d47cfab10f5ad45db3c3b02e | ksh1ng/python_Exercise | /multiplicationtable.py | 203 | 3.8125 | 4 | import string
def multiple(n):
row = ''
for i in range(1,13):
row += str(i) + "*" + str(n) + " = " + str(i*n) + "\t"
print(row.ljust(3))
for j in range(1,13):
multiple(j)
|
45bb75a0276923b3bf5066d1d467889a0aa20fff | GARV3007/Data-Mining-codes | /Week 4/Exercise_7.2.2.py | 1,367 | 3.71875 | 4 | """
Gourav Verma
DSC550 - Data Mining
Summer - 2020
Week-2 : Exercise- 7.2.2 : Hierarchical Clustering
Book - Mining of Massive Datasets
"""
"""
Exercise 7.2.2 : How would the clustering of Example 7.2 change if we used
for the distance between two clusters:
(a) The minimum of the distances between any two points, one from each
cluster.
(b) The average of the distances between pairs of points, one from each of the
two clusters.
"""
from sklearn.cluster import AgglomerativeClustering
import numpy as np
from matplotlib import pyplot as plt
from scipy.cluster.hierarchy import dendrogram
pt = np.array([[2, 2], [3, 4], [5, 2], [4, 8], [4, 10], [6, 8], [7, 10], [9, 3], [10, 5], [12, 6], [11, 4], [12, 3]])
model = AgglomerativeClustering(affinity='euclidean', linkage='average')
model = model.fit(pt)
# Children of hierarchical clustering
children = model.children_
# Distances between each pair of children
# Since we don't have this information, we can use a uniform one for plotting
distance = np.arange(children.shape[0])
# The number of observations contained in each cluster level
no_of_observations = np.arange(2, children.shape[0]+2)
# Create linkage matrix and then plot the dendrogram
linkage_matrix = np.column_stack([children, distance, no_of_observations]).astype(float)
# Plot the corresponding dendrogram
dendrogram(linkage_matrix)
plt.show()
|
72eecbcd086cbd4187e9e20a0be75b59bf21109c | nicolas-tdc/python-exercism | /_DONE/bob/bob.py | 522 | 3.734375 | 4 | """Bob"""
def response(hey_bob):
"""
:param hey_bob: string
:return: string - Bob's response
"""
hey_bob = hey_bob.strip()
if hey_bob.isupper() and hey_bob.endswith('?'):
response = 'Calm down, I know what I\'m doing!'
elif hey_bob.isupper():
response = 'Whoa, chill out!'
elif hey_bob.endswith('?'):
response = 'Sure.'
elif hey_bob.isspace() or not hey_bob:
response = 'Fine. Be that way!'
else:
response = 'Whatever.'
return response
|
453d398dd7e6c31514d7262590a48daf020b34ff | smwelisson/Exercicio_CeV | /19 - Dicionarios 90 - 95/Aula 19 Dicionarios.py | 851 | 3.875 | 4 | # print(filme)
# print(filme.values())
# print(filme.keys())
# print(dir(filme))
# filme = {'titulo': 'starwars', 'ano': 1977, 'diretor': 'George Lucas'}
# print(filme.items())
# print("")
# for keys, values in filme.items():
# print(f"O {keys} é {values}")
# pessoas = {'nome': 'Well', 'sexo': 'M', 'idade': 28}
# print(f"O {pessoas['nome']} tem {pessoas['idade']} anos")
# print(pessoas.keys())
# print(pessoas.values())
# print(pessoas.items())
# pessoas['nome'] = 'Cell'
# pessoas['novo item'] = 'um novo item'
# for k, v in pessoas.items():
# print(f"{k} = {v}")
estado = dict()
brasil = list()
for cap in range(3):
estado['uf'] = str(input("Unidade Federativa: "))
estado['sigla'] = str(input("Sigla do Estado: "))
brasil.append(estado.copy())
for e in brasil:
for v in e.values():
print(v, end=" - ")
print()
|
1b1789428f50df3f7dbc88933b25818f8f0db094 | pite2019/pite2019s-t1-g1-jc97 | /matrix.py | 4,290 | 3.59375 | 4 | #!/usr/bin/python3
from typing import List
class Matrix:
__lines = ... # type: int
__columns = ... # type: int
__matrix = ... # type: List[List[int]]
def __init__(self, lines, columns):
if not isinstance(lines, int) or lines < 1 or not isinstance(columns, int) or columns < 1:
raise ValueError()
self.__lines = lines
self.__columns = columns
self.__matrix = []
self.__num = 0
for i in range(0, lines):
self.__matrix.append([])
for j in range(0, columns):
self.__matrix[i].append(0)
def set_values(self, values):
if not isinstance(values, List) or len(values) != self.__lines:
raise ValueError()
for line in values:
if not isinstance(line, List) or len(line) != self.__columns:
raise ValueError()
for value in line:
if not isinstance(value, int) and not isinstance(value, float):
raise ValueError()
self.__matrix = values
def add_matrix(self, summand):
if not isinstance(summand, Matrix) or summand.__lines != self.__lines or summand.__columns != self.__columns:
raise ValueError()
for i in range(0, self.__lines):
for j in range(0, self.__columns):
self.__matrix[i][j] += summand.__matrix[i][j]
def subtract_matrix(self, subtrahend):
if not isinstance(subtrahend, Matrix) or subtrahend.__lines != self.__lines or subtrahend.__columns != self.__columns:
raise ValueError()
for i in range(0, self.__lines):
for j in range(0, self.__columns):
self.__matrix[i][j] += subtrahend.__matrix[i][j]
def __add__(self, summand):
numeric_summand = False
if isinstance(summand, float) or isinstance(summand, int):
numeric_summand = True
elif not isinstance(summand, Matrix) or summand.__lines != self.__lines or summand.__columns != self.__columns:
raise ValueError()
result = Matrix(self.__lines, self.__columns)
for i in range(0, self.__lines):
for j in range(0, self.__columns):
if numeric_summand:
result.__matrix[i][j] = self.__matrix[i][j] + summand
else:
result.__matrix[i][j] = summand.__matrix[i][j] + self.__matrix[i][j]
return result
def __radd__(self, other):
return self.__add__(other)
def __sub__(self, subtrahend, invert=False):
numeric_subtrahend = False
if isinstance(subtrahend, float) or isinstance(subtrahend, int):
numeric_subtrahend = True
elif not isinstance(subtrahend, Matrix) or subtrahend.__lines != self.__lines \
or subtrahend.__columns != self.__columns:
raise ValueError()
result = Matrix(self.__lines, self.__columns)
for i in range(0, self.__lines):
for j in range(0, self.__columns):
if numeric_subtrahend:
result.__matrix[i][j] = (self.__matrix[i][j] - subtrahend) * (-1 if invert else 1)
else:
result.__matrix[i][j] = (self.__matrix[i][j] - subtrahend.__matrix[i][j]) * (-1 if invert else 1)
return result
def __rsub__(self, other):
return self.__sub__(other, True)
def multiply(self, multiplicand):
if isinstance(multiplicand, int) or isinstance(multiplicand, float):
result = Matrix(self.__lines, self.__columns)
for i in range(self.__lines):
for j in range(self.__columns):
result.__matrix[i][j] = self.__matrix[i][j] * multiplicand
return result
elif not isinstance(multiplicand, Matrix) or multiplicand.__lines != self.__columns:
raise ValueError()
result = Matrix(self.__lines, multiplicand.__columns)
for i in range(result.__lines):
for j in range(result.__columns):
value = 0
for k in range(self.__columns):
value += self.__matrix[i][k] * multiplicand.__matrix[k][j]
result.__matrix[i][j] = value
return result
def __matmul__(self, other):
return self.multiply(other)
def __imatmul__(self, other):
return self.multiply(other)
def __rmatmul__(self, other):
if isinstance(other, int) or isinstance(other, float):
return self.multiply(other)
elif isinstance(other, Matrix):
return other.multiply(self)
else:
raise ValueError()
def print_matrix(self):
for i in range(0, self.__lines):
for j in range(0, self.__columns):
print(str(self.__matrix[i][j]) + " ", end='')
print("\n", end='')
print("")
def __iter__(self):
return self
def __next__(self):
if self.__num < self.__lines:
self.__num += 1
return self.__matrix[self.__num - 1]
else:
raise StopIteration()
|
51f66ab2496dfbd2170e2843c9070ded5a6b4325 | aurlien/AdventOfCode2020 | /d11/ex2.py | 2,527 | 3.546875 | 4 | FLOOR = '.'
SEAT_EMPTY = 'L'
SEAT_OCCUPIED = '#'
UP = -1
DOWN = +1
RIGHT = +1
LEFT = -1
def parse_input(filename):
with open(filename) as f:
return [list(line.strip()) for line in f.readlines()]
def print_grid(grid):
for line in grid:
print("".join(line))
print()
def adjacent(row, col, grid):
ROW_MAX = len(grid)
COL_MAX = len(grid[0])
def next(row, col, dx=0, dy=0):
x = row + dx
y = col + dy
seat = grid[x][y] if (0 <= x < ROW_MAX) and (0 <= y < COL_MAX) else None
if seat == FLOOR:
seat = next(row + dx, col + dy, dx, dy)
return seat
right = lambda row, col: next(row, col, dy=RIGHT)
left = lambda row, col: next(row, col, dy=LEFT)
up = lambda row, col: next(row, col, dx=UP)
down = lambda row, col: next(row, col, dx=DOWN)
up_left = lambda row, col: next(row, col, dx=UP, dy=LEFT)
down_left = lambda row, col: next(row, col, dx=DOWN, dy=LEFT)
up_right = lambda row, col: next(row, col, dx=UP, dy=RIGHT)
down_right = lambda row, col: next(row, col, dx=DOWN, dy=RIGHT)
seats = [fun(row, col) for fun in [up, down, left, right, up_left, up_right, down_left, down_right]]
return list(filter(lambda s: s != None and s != FLOOR, seats))
def all_empty(adjacent):
return all(map(lambda x: x == SEAT_EMPTY, adjacent))
def at_least_five_occupied(adjacent):
return len(list(filter(lambda x: x == SEAT_OCCUPIED, adjacent))) >= 5
def model_round(grid):
new_grid = []
for r, row in enumerate(grid):
new_row = []
for c, seat in enumerate(row):
if seat == FLOOR:
new_row.append(FLOOR)
else:
a = adjacent(r, c, grid)
if seat == SEAT_EMPTY and all_empty(a):
new_row.append(SEAT_OCCUPIED)
elif seat == SEAT_OCCUPIED and at_least_five_occupied(a):
new_row.append(SEAT_EMPTY)
else:
new_row.append(seat)
new_grid.append(new_row)
new_row = []
return new_grid
def count_occupied(grid):
return sum([sum([True for seat in row if seat == SEAT_OCCUPIED]) for row in grid])
def run_model(grid):
next_grid = model_round(grid)
if next_grid == grid:
return grid
return run_model(next_grid)
def main():
grid = parse_input("input.txt")
stable_grid = run_model(grid)
return count_occupied(stable_grid)
print(main()) |
51ae5cf166e0c1efb19d1b42fd9986f062dd0f9f | lunadata/4linux | /aula5/orientacao_objeto_ex.py | 576 | 3.6875 | 4 | class Pessoa():
#Construtor
def __init__(self, nome = '', sexo = '', peso = '', cor = '', nacionalidade = ''):
self.nome = nome
self.sexo = sexo
self.peso = peso
self.cor = cor
self.nacionalidade = nacionalidade
#Criar métodos
def falar(self):
self.peso = 30
if self.peso >= 120:
print('Obeso')
else:
print('Dentro do peso')
#Instanciando um objeto
joao = Pessoa('Joao', 125, 'Parda', 'Alema')
print(joao.nome)
print(joao.falar)
joao.falar()
|
bc02f044aab075d791784c4aeb6d8755e95cf38e | NickStrick/Code-Challenges | /CodeWars/TribonacciSequence.py | 366 | 4.0625 | 4 | def tribonacci(signature, n):
if n == 0:
return []
if n <= 3:
return signature[:n]
# your code here
print(signature, n)
while len(signature) < n:
index = len(signature)
value = signature[index-1] + signature[index-2] + signature[index-3]
signature.append(value)
# print(signature)
return signature
|
717e3027766893297b350d29a442b6209bc08b2c | VincentJ1989/PythonTutorial | /chapter7/trans_array.py | 546 | 3.9375 | 4 | # 传递列表
def greet_users(names):
for name in names:
print('Hello,' + name)
users = ['Lily', 'Tom', 'Jerry']
greet_users(users)
# 在函数中修改列表
old_data = ["a", 'b', 'c']
new_data = []
def change(values):
while values:
new_data.append(values.pop())
change(old_data)
print(new_data)
print(old_data)
# 有时需要禁止函数修改列表--永久性的
old = ['1', '2', '3']
new = []
def stay_same(nums):
while nums:
new.append(nums.pop())
stay_same(old[:])
print(new)
print(old)
|
a9c1cbfe09cb4b1225c78ed5083b2531258e491b | rtelles64/BookStore | /Bookstore/frontend.py | 4,696 | 4.0625 | 4 | '''
This is our GUI file (the main file to run)
A program that stores this book information:
Title
Author
Year
ISBN
User can:
View all records
Search an entry
Update entry
Delete entry
Close
'''
from tkinter import *
from backend import Database # import Database class from backend script
# create a Database object
database = Database("books.db")
'''
Where we write our command (wrapper) functions
'''
def get_selected_row(event):
try: # try to execute indented block
global selected_tuple # makes this a global variable
index = list1.curselection()[0] # as prints out tuple
selected_tuple = list1.get(index)
e1.delete(0, END)
e1.insert(END, selected_tuple[1])
e2.delete(0, END)
e2.insert(END, selected_tuple[2]) # grab the author name
e3.delete(0, END)
e3.insert(END, selected_tuple[3]) # grab the year
e4.delete(0, END)
e4.insert(END, selected_tuple[4]) # grab the isbn
except IndexError: # except when there is an index error
pass # do nothing
def view_command():
list1.delete(0, END) # ensures we delete everything from 0 to last row
# so as to not print duplicates (edge case)
for row in database.view():
list1.insert(END, row) # new rows will be put at the END of the listbox
def search_command():
list1.delete(0, END) # empty the list
for row in database.search(title_text.get(), author_text.get(),\
year_text.get(), isbn_text.get()):
list1.insert(END, row)
def add_command():
database.insert(title_text.get(), author_text.get(),\
year_text.get(), isbn_text.get())
list1.delete(0, END)
# let user know the add was successful by displaying entry information
list1.insert(END, (title_text.get(), author_text.get(),\
year_text.get(), isbn_text.get()))
def delete_command():
database.delete(selected_tuple[0])
def update_command():
database.update(selected_tuple[0], title_text.get(), author_text.get(),\
year_text.get(), isbn_text.get())
'''
END command functions
'''
window = Tk() # creates a window
window.wm_title("Book Store") # adds title to window's title bar
''' Create labels '''
# create a Title label
l1 = Label(window, text = "Title")
# use grid method to set its place in the window
l1.grid(row = 0, column = 0)
# create Author label
l2 = Label(window, text = "Author")
l2.grid(row = 0, column = 2)
# create Year label
l3 = Label(window, text = "Year")
l3.grid(row = 1, column = 0)
# create ISBN label
l4 = Label(window, text = "ISBN")
l4.grid(row = 1, column = 2)
''' Add entry fields '''
title_text = StringVar() # this line is required!
e1 = Entry(window, textvariable = title_text)
e1.grid(row = 0, column = 1)
author_text = StringVar() # this line is required!
e2 = Entry(window, textvariable = author_text)
e2.grid(row = 0, column = 3)
year_text = StringVar() # this line is required!
e3 = Entry(window, textvariable = year_text)
e3.grid(row = 1, column = 1)
isbn_text = StringVar() # this line is required!
e4 = Entry(window, textvariable = isbn_text)
e4.grid(row = 1, column = 3)
''' Create list box '''
list1 = Listbox(window, height = 6, width = 35)
#list1.grid(row = 2, column = 0) # Note: this format occupies only the first cell!
list1.grid(row = 2, column = 0, rowspan = 6, columnspan = 2)
''' Create scrollbar '''
sb1 = Scrollbar(window) # window parameter attaches our object to window
sb1.grid(row = 2, column = 2, rowspan = 6) # helps to draw a grid to visualize
list1.configure(yscrollcommand = sb1.set) # vertical scroll bar set to sb1
sb1.configure(command = list1.yview) # we pass a command parameter, which means
# when we scroll the bar, the vertical view
# of the list will change
list1.bind('<<ListboxSelect>>', get_selected_row)
''' Create buttons '''
b1 = Button(window, text = "View all", width = 12, command = view_command)
b1.grid(row = 2, column = 3)
b2 = Button(window, text = "Search entry", width = 12, command = search_command)
b2.grid(row = 3, column = 3)
b3 = Button(window, text = "Add entry", width = 12, command = add_command)
b3.grid(row = 4, column = 3)
b4 = Button(window, text = "Update selected", width = 12, command = update_command)
b4.grid(row = 5, column = 3)
b5 = Button(window, text = "Delete selected", width = 12, command = delete_command)
b5.grid(row = 6, column = 3)
b6 = Button(window, text = "Close", width = 12, command = window.destroy)
b6.grid(row = 7, column = 3)
window.mainloop() # keeps window open until closed by user
|
2cc0a8aa559d4349d2300fc4e02ae7bcab18462f | saifazmi/learn | /languages/python/sentdex/basics/63_exec.py | 766 | 4.125 | 4 | # Using Exec
'''
' exec() is a built-in function and is perhaps the most dangerous yet cool
' thing, as it is step-up from eval() since it compiles and evaluates
' whatever is passed through in string form; essentially acting as a compiler
' inside a compiler. So be very carefull on web-server, virual machines, etc.
'''
exec("print('so this works like eval')")
list_str = "[5,6,2,1,2]"
list_str = exec(list_str) # None, because this is the action of defining a list
print(list_str)
exec("list_str2 = [5,6,2,1,2]") # defines and assigns i.e. execution over eval
print(list_str2) # will print the list
# defining functions
exec("def test(): print('hot diggity')")
test()
exec("""
def test2():
print('testing to see if multiple lines work...')
""")
test2()
|
b55630e35027e623661fdb23ac26cf1be87ba802 | rhtrka15/running_py | /Py_1111/Py_1111/Py_1111.py | 2,632 | 3.6875 | 4 | #물건 값을 입력하고 낸 돈을 확인후 거스름 돈의 동전을 구분하는 프로그램
AB=int(input("물건 값을 입력하시오. :"))
t=int(input("1000원 지폐 개수 :"))
fh=int(input("500원 동전의 개수 :"))
h=int(input("100원 동전의 개수 :"))
_1000=t*1000
_500=fh*500
_100=h*100
rus=_1000+_500+_100
print("500원의 개수:"rus//500)
re=rus%500
print("100원의 개수"re//100)
bb=re%100
print("50원의 개수:"bb//50)#
#abcd의 연산후 a와 b의 크기를 구분하는 프로그램
a=10
b=20
c=30
d=40
a,b=b,a
a,b,c,d=d,c,b,a
print(a,b,c,d)
if(a>b):
print("a가 b보다 큽니다.")
else:
print("b가 a보다 큽니다.")
#import를 통해 tutle을 불러내어 조금한 게임을 구현하는 프로그램
import turtle
t=turtle,pen()
while True:
direction=input("왼쪽=left, 오른쪽=right :")
if direction=="l":
t.left(60)
t.forward(50)
if direction=="r":
t.right(60)
t.forward(50)
#while문을 이용한홀수와 짝수를 구별하는 프로그램
a=1
while a<10:
b=int(input("정수를 입력해 주십시오 :"))
c=b%2
if c==1:
print("홀수입니다.")
else:
print("짝수입니다.")
a+=1
#구입 금액이 10만원 이상일때 할인이된 최종 가격을 말하고 이하면 그냥 가격을 출력하는 프로그램
A=int(input("구입 금액을 입력하시오 :"))
if A>100000:
dis=A*0.05
c=A-dis
print("할인 가격은"c"입니다.")
#학점과 평점을 계산하여 졸업의 유무를 구분하는 프로그램
to=int(input("이수한 학점수를 입력하십시오 :"))
pp=float(input("평점을 입력하십시오 :"))
if to>140 and pp>2.0:
print("졸업이 가능합니다! ㅊㅊ")
else:
print("졸업이 불가능 합니다..! ㅠㅠ")
#dateime 을 import 하여 현재의 시간 분 초를 나타내는 프로그램.
import datetime
now = datetime.datetime.now()
print(now.hour,"시")
print(now.minute,"분")
print(now.second,"초")
#datetime 을 improt 하여 if문을 사용해 계절을 구분하는 프로그램
if 3<= now.month <=5:
print("이번 달은 {}월로 봄입니다!".format(now.month))
if 6<= now.month <=8:
print("이번 달은 {}월로 여름입니다!".format(now.month))
if 9<= now.month <=11:
print("이번 달은 {}월로 가을입니다!".format(now.month))
if 12 or 1 <= now.month <=2:
print("이번 달은 {}월로 겨울입니다!".format(now.month))
#from random or import random 랜덤 사용법
#random=randint(1,100) random.randint(0,2) 랜덤 사용법
|
bb8537c4a3739ed98a654a94b59e349e21bb860a | zehraturan/Python-Assignments | /Prime_Number2.py | 391 | 3.765625 | 4 | n= int(input("which are between 1 to 100: "))
prime = []
for i in range(1,n+1) :
if i == 2 :
prime.append(i)
elif i % 2 :
control = True
if i == 1 :
control = False
else :
j = 2
while j < i / 2 :
if (i / j).is_integer() :
control = False
break
j+=1
if control :
prime.append(i)
print(prime) |
b4554a7c2ece968593885d5654ae55d8befc7810 | kimmanbo/cheat-sheet | /python3/singleton/thread-safe-singleton.py | 542 | 3.53125 | 4 | from threading import RLock
class Singleton(type):
_instance = None
_lock = RLock()
def __call__(cls, *args, **kwargs):
with cls._lock:
if not cls._instance:
cls._instance = super().__call__(*args, **kwargs)
return cls._instance
class SingletonClass(metaclass=Singleton):
def __init__(self, name):
self.name = name
def main():
obj1 = SingletonClass("A")
print(obj1.name)
obj2 = SingletonClass("B")
print(obj2.name)
if __name__ == "__main__":
main()
|
f2731d4c3173c70372c4ccb8baa362f2e4b8f538 | ad002/LPTHW | /ex27.py | 251 | 3.515625 | 4 | #The Truth Terms
#In Python we have the following terms for determining if smth. is true or
#false
# and
# or
# not
# != (not equal)
# == (equal)
# >= (greater-than-equal)
# <= (less-than-equal)
# True
# False
|
5d80299f158ce936e915d57107a504874b59fc85 | ijkilchenko/numpy_or_bust | /mcmc.py | 2,053 | 3.8125 | 4 | import numpy as np
from collections import defaultdict
def f(x):
"""This is the function f(x) which is proportional to some P(x).
In this example, consider 5 points in a circle as our space. We
do not know the actual probability distribution, but we do know
some relative probabilities. """
return _f()[x]
def next_x_given_x(x, width=2):
"""This gives the next point located normally (rounded to nearest integer)
around x. This is the jumping distribution. """
num_points = len(_f())
next_x = round(np.random.normal()*width)
# Loop around since our points are in a circle.
# Note: this works with negative numbers too.
return next_x % num_points
def metropolis(fun=f, num_iter=10000):
"""fun is the function f(x) which is proportional to some P(x) which we
are trying to approximate. """
num_points = len(_f())
x = np.random.randint(num_points) # Starting point.
# We count how many times we observe each point in the Markov sequence.
bins_of_samples = defaultdict(lambda: 0)
# Could be less than num_iter because we reject some samples.
for i in range(num_iter):
next_x = next_x_given_x(x)
acceptance_ratio = fun(next_x)/fun(x) # = P(next_x)/P(x).
if acceptance_ratio >= 1 or np.random.uniform() < acceptance_ratio:
# Accept next_x.
x = next_x
else:
# Reject next_x.
pass
bins_of_samples[x] += 1 # Count this sample.
stationary_distribution = [bins_of_samples[p]/num_iter
for p in bins_of_samples]
return stationary_distribution
if __name__ == '__main__':
for D in [[89, 77, 84, 1, 30],
[89, 77, 84, 1, 300]]:
def _f():
return D
print('Target distribution: ')
denominator_P = sum(_f())
print([float('%.2f' % round(x/denominator_P, 2)) for x in _f()])
print('Stationary distribution: ')
print([round(x, 2) for x in metropolis()])
print()
|
aed95ed696b0b89266a66d58f44c42d84fb57a4c | MuhammadMajidAltaf/serial_processors_project | /tools/candidate_finder/candidate_finder.py | 1,848 | 3.890625 | 4 | import sys
from os import listdir
from os.path import join, splitext
def candidate_finder(base_dir, min_val, max_val):
"""
Produce a list of files that have line length between min_val and max_val.
Providing a quick way to cull a lot of very simple examples quickly to focus
on differentiating the more complex cases.
:param base_dir: A directory to search, can be provided either absolute or
relative though absolute is preferred.
:param min_val: An integer to represent the minimum number of lines to
be considered
:param max_val: An integer to represent the maximum number of lines to be
considered.
:return: Nothing.
"""
# Grab a list of all the files in a directory only if the file extension is
# asm.
asm_files = [f for f in listdir(base_dir)
if splitext(f)[-1].lower().endswith("asm")]
# Create a list to hold all the results
results = []
# Iterate over the asm files
for asm_file in asm_files:
# Count how many lines are in each file
num_lines = sum(1 for _ in open(join(base_dir, asm_file)))
# If the number of lines is within the given interval then append the
# file and how many lines it has to the results list
if min_val <= num_lines <= max_val:
results.append([asm_file, num_lines])
# Sort the files that have been found by the number of lines they have
final_results = sorted(results, key=lambda pulled_result: pulled_result[1])
# Print out each one in turn.
for result in final_results:
print("Name: {0}, Number of Lines: {1}".format(result[0], result[1]))
return
if __name__ == "__main__":
# Call the candidate finder with all the arguments as given on the command
# line.
candidate_finder(sys.argv[1], int(sys.argv[2]), int(sys.argv[3]))
|
9a3c9c9ee1d31d1495dbd834e577c4106911de30 | daniel-reich/ubiquitous-fiesta | /4WNkqa5Pb6Lh6ZXvs_20.py | 471 | 3.90625 | 4 |
def evaluate_polynomial(poly, num):
x= num; pos = []
for change in [('^', '**'),('(', '*('),('//', '//^')]:
s = 0
while s >= 0:
s = poly.find(change[0], s)
if s != -1: poly = poly[:s]+change[1]+poly[s+1:]; s=s+2
for let in enumerate(poly[:-1]):
if let[1].isnumeric() and poly[let[0]+1] == 'x': pos.append(let[0]+1)
while pos: change = pos.pop(); poly = poly[:change]+'*'+poly[change:]
try: return eval(poly)
except: return "invalid"
|
f4635007f8819e5178b63ff3087c865051b040bd | arironman/MSU-Python | /ex-8/34.py | 332 | 4.3125 | 4 | #ASCII=American Standard Code for Information Interchange
#ASCII code start from 0 and end at 255
#chr(ascii code) function used to convert ASCII Code to respective character
#ord("Character") function used to convert Character to respective ASCII code
for x in range(0,256):
print(f"ASCII code of {chr(x)} is {x}")
|
e1ecb3784e98fbbdd26783c0ffaef08ef3c57c5c | zhangli709/python_note | /day10/rectangle.py | 2,256 | 3.984375 | 4 | class Rectangle(object):
def __init__(self, height, width, color, position):
self._height = height
self._width = width
self._color = color
self._position = position
def perimeter(self):
print('周长为%s' % ((self._height + self._width) * 2))
def area(self):
"""
计算面积
:return: 面积
"""
print('面积为%s' % (self._height * self._width))
def main():
recta1 = Rectangle(10, 20, 'blue', 'right')
recta1.perimeter()
recta1.area()
recta2 = Rectangle(15, 10, 'orange', 'middle')
recta2.perimeter()
recta2.area()
class Timer(object):
def __init__(self, hour=0, minute=0, second=0):
self._hour = hour
self._minute = minute
self._second = second
def run(self):
"""
走字
:return:
"""
self._second += 1
if self._second == 60:
self._second = 0
self._minute += 1
if self._minute == 60:
self._minute = 0
self._hour += 1
if self._hour == 24:
self._hour = 0
def show(self): # ** def __str__(self): 此方法可以获得对象的字符串表达形式,当我们用print打印对象时,会自动调用该方法。
"""
显示时间
:return:
"""
return '%02d:%02d:%02d' % \
(self._hour, self._minute, self._second) # 换行的方法。
from math import pi
# 我们定义一个类,实际上是把数据和操作数据的函数绑定在一起,
# 形成一个逻辑上的整体,这个整体就叫对象
# 而且将来想要使用这个对象时,直接使用这个类就行了。
class Circle(object):
def __init__(self, radius):
self._radius = radius
def area(self):
return pi * self._radius ** 2
def perimeter(self):
return pi * self._radius * 2
def main():
r = float(input('请输入游泳池的半径:'))
big = Circle(r+3)
small = Circle(3)
print('围墙的造价为%.2f元' % (big.perimeter() * 32.5))
print('过道的造价为%.2f元' % ((big.area()-small.area()) * 32.5))
if __name__ == '__main__':
main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.