text
stringlengths 37
1.41M
|
---|
import logging
import threading
import time
logging.basicConfig(level=logging.DEBUG,
format='(%(threadName)-2s) %(message)s')
class Taller(object):
def __init__(self, start=0):
self.condicionMangasMAX = threading.Condition()
self.condicionMangasMIN = threading.Condition()
self.mangas = 0
self.cuerpos = 0
def incrementarManga(self):
with self.condicionMangasMAX:
if self.mangas >= 10:
logging.debug("No hay espacio para mangas")
self.condicionMangasMAX.wait()
else:
self.mangas += 1
logging.debug("Manga creada, mangas=%s", self.mangas)
with self.condicionMangasMIN:
if self.mangas >= 2:
logging.debug("Existen suficientes mangas")
self.condicionMangasMIN.notify()
def decrementarManga(self):
with self.condicionMangasMIN:
while not self.mangas >= 2:
logging.debug("Esperando mangas")
self.condicionMangasMIN.wait()
self.mangas -= 2
logging.debug("Mangas tomadas, mangas=%s", self.mangas)
with self.condicionMangasMAX:
logging.debug("Hay espacio para mangas")
self.condicionMangasMAX.notify()
def getMangas(self):
return (self.mangas)
def crearCuerpo(self):
self.cuerpos += 1
def crearManga(Taller):
while (Taller.getMangas() <= 10):
Taller.incrementarManga()
time.sleep(5)
def tomarMangas(Taller):
while (taller.getMangas() >= 0):
Taller.decrementarManga()
time.sleep(1)
def crearCuerpos(Taller):
logging.debug('Creando cuerpos')
taller = Taller()
mangas = threading.Thread(name='personaMangas', target=crearManga, args=(taller,))
tomarM = threading.Thread(name='tomarMangas', target=tomarMangas, args=(taller,))
# cuerpos = threading.Thread(name='personaCuerpos', target=crearCuerpos(taller))
mangas.start()
tomarM.start()
tomarM.join()
mangas.join()
|
#Программы,которые предстоит мне сделать
#Нормальный калькулятор с интерфейсом
#Змейка
#Тетрис
#Игру, где нужно угадать число, загаданное компьютером
#Сумма натуральных чисел в заданном диапазоне. Дата: ?
num = []
for value in range(1,3002):
num.append(value)
print(sum(num))
#Игра где нужно угадать число, загаданное компьютером. Дата: 5.12.2020г.
import random
from random import randint
#Генерируем число
number = random.randint(1,10001)
print("Let's go!!!")
#Просим ввести число
def rand_number() :
what = int(input('\tВведите число: '))
#Выводим результат при разных значениях
if what < number:
print('Больше')
rand_number()
elif what > number:
print('Меньше')
rand_number()
else:
print('You win!')
rand_number()
|
def soma(entradas, pesos):
soma = 0
for i, j in zip(entradas, pesos):
soma += i * j
return soma
def step_function(soma):
return soma >= 1
entradas = [-1, 7, 5]
pesos = [0.8, 0.1, 0]
soma = soma(entradas, pesos)
print("Resultado da soma:")
print(soma)
resultado = step_function(soma)
print("Resultado da função de ativação:")
print(resultado)
|
import socket
import time
HEADERSIZE = 10
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #AF_INET = ipv4, Stock_stream = tcp
s.bind((socket.gethostname(),1239)) # 1234 --> PORT Number ## The bind() method of Python's socket class assigns an IP address and a port number to a socket instance. The bind() method is used when a socket needs to be made a server socket. As server programs listen on published ports, it is required that a port and the IP address to be assigned explicitly to a server socket.
s.listen(5) # listen --> It listens for connections from clients. A listening socket does just what it sounds like. It listens for connections from clients. When a client connects, the server calls accept() to accept, or complete, the connection. The client calls connect() to establish a connection to the server and initiate the three-way handshake.
while True:
clientsocket,address = s.accept()
print(f"Connection from {address} established !")
msg = "Welcome to the server!"
msg = f'{len(msg):<{HEADERSIZE}}'+msg
clientsocket.send(bytes(msg,"utf-8"))
while True:
time.sleep(3)
msg = f"The time is {time.time()}"
msg = f'{len(msg):<{HEADERSIZE}}'+msg
clientsocket.send(bytes(msg,"utf-8"))
|
# Task
# You are given a string. Split the string on a " " (space) delimiter and join using a - hyphen.
# Function Description
# Complete the split_and_join function in the editor below.
# split_and_join has the following parameters:
# string line: a string of space-separated words
# Returns
# string: the resulting string
# Input Format
# The one line contains a string consisting of space separated words.
# Sample Input
# this is a string
# Sample Output
# this-is-a-string
def split_and_join(line):
l = line.split(" ")
b = ""
for i in l:
b = b + "-" + i
b = b[1:]
return b
if __name__ == '__main__':
line = input()
result = split_and_join(line)
print(result) |
squares = [1, 4, 9, 16, 25]
squares.append(36);
print(squares)
print(squares[1])
print(squares[-3:])
# return a new copy of the list
sq = squares[:]
squares.append(49)
print(sq)
squares = squares + [36, 49, 64, 81, 100]
print(squares)
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
letters[2:5] = ['C', 'D', 'E']
print(letters)
print(letters[2:5])
letters[2:5] = []
print(letters)
letters = 12;
print(letters)
original=[1,2,3]
original[len(original):]=[4,5]
print(original[2:])
original.extend([6,7,8])
print(original)
print(original.pop(0))
print(original.pop())
original.sort(reverse=True)
from collections import deque
print(original)
queue = deque(["Eric", "John", "Michael"])
print(queue.popleft())
# list comprehensions
compre = [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
print(compre)
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
]
list = [[row[i] for row in matrix] for i in range(4)]
print(list)
del list[2:4]
print(list)
# unpacking a list into multiple variables
m,n = list
print(m) |
"""
Helpers
"""
import time
from functools import wraps
class TimeRec:
"""
Calculate time of excecution. How to use it:
tm = TimeRec() # (1)
...
exec_time = tm.step() # (2) exec_time is time from (1) to (2)
...
exec_time2 = tm.step() # (3) exec_time is time from (2) to (3)
...
tot_time = tm.total() # (4) exec time from (4) to (1)
print(tm) # print total time
"""
def __init__(self):
self._time0 = time.monotonic()
self._last = self._time0
def step(self):
delta = time.monotonic() - self._last
self._last = time.monotonic()
return delta
def total(self):
return time.monotonic() - self._time0
def __str__(self):
return 'Total: {:.3f} sec'.format(self.total())
def frozen_cls(cls):
""" Well-known solution how to prevent addition of new attributes
to a class without using 'slot'.
This is a decorator and should be used like this:
@frozen_cls
class Klass:
...
cls = Klass()
cls.x = 'X' # it is possible only for members defined in class.
"""
cls.__frozen = False
def frozen_attr(self, key, value):
if not hasattr(self, key) and self.__frozen:
raise AttributeError("Could not set new attribute '{}' "
"for frozen class '{}'".format(key, cls.__name__))
else:
object.__setattr__(self, key, value)
def init_wrapper(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
func(self, *args, **kwargs)
self.__frozen = True
return wrapper
cls.__setattr__ = frozen_attr
cls.__init__ = init_wrapper(cls.__init__)
return cls |
# The basic approach of this alogorithm is to rollback to previous step if the current step is not going to give you a correct solution
def can_be_extended_to_solution(perm):
"""This function checks whether the solution is correct i.e if any the queen placed in current step is attacked by previously placed queens
Args:
perm (list): it takes the list of available permutations
Returns:
boolean: Either True(can be extended to solution) or False(cannot be extended to a solution)
"""
# check if last queen is attacked by previous queens
# for this store index of queens excpet last one
i = len(perm) - 1
# loop through the index of queens
for j in range(i):
# if they're in diagonal then it can't be extended to a solution so return False
if i - j == abs(perm[i] - perm[j]):
return False
# if all no queens are in diagonal or attack the last queen then the solution is correct i.e return True
return True
def extend(perm, n):
"""This function uses recursion to check if the solution is correct if the solution is correct prints the solution and exits
Args:
perm (list): list containing the permutations
n (int): integer that store the no of square in each side of a board
"""
# if length of the permutations is equal to the length of the board i.e n then no longer to extend solution
# print the result and return
if len(perm) == n:
print(perm)
return # in this case we print all the available solutions
exit() # breaks out of loop to print only one solution
# loop through the index n
for k in range(n):
# if the index already presents then we don't want to add again to the list
# so check if the index is in list or not
if k not in perm:
# if index not in list append it to the list
perm.append(k)
# call ca_be_extended_to_solution with current list to see if it is correct
# if no conflict occurs proceed otherwise remove that element and check the previous step for solution
if can_be_extended_to_solution(perm):
extend(perm, n)
perm.pop()
print(extend(perm = [], n = 8)) |
#!/usr/bin/python
"""
Princess Peach is trapped in one of the four corners of a square grid. You are in the center of the grid and can move one step at a time in any of the four directions. Can you rescue the princess?
Input format
The first line contains an odd integer N (3 <= N < 100) denoting the size of the grid. This is followed by an NxN grid. Each cell is denoted by '-' (ascii value: 45). The bot position is denoted by 'm' and the princess position is denoted by 'p'.
Grid is indexed using Matrix Convention
Output format
Print out the moves you will take to rescue the princess in one go. The moves must be separated by '\n', a newline. The valid moves are LEFT or RIGHT or UP or DOWN.
Sample input
3
---
-m-
p--
Sample output
DOWN
LEFT
Task
Complete the function displayPathtoPrincess which takes in two parameters - the integer N and the character array grid. The grid will be formatted exactly as you see it in the input, so for the sample input the princess is at grid[2][0]. The function shall output moves (LEFT, RIGHT, UP or DOWN) on consecutive lines to rescue/reach the princess. The goal is to reach the princess in as few moves as possible.
The above sample input is just to help you understand the format. The princess ('p') can be in any one of the four corners.
Scoring
Your score is calculated as follows : (NxN - number of moves made to rescue the princess)/10, where N is the size of the grid (3x3 in the sample testcase).
https://www.hackerrank.com/challenges/saveprincess/problem
"""
def displayPathtoPrincess(n,grid):
p = [0,0]
b = [0,0]
path = []
for row in range(n):
for col in range(n):
if grid[row][col] == 'm':
b = [row, col]
if grid[row][col] == 'p':
p = [row, col]
# print(p, b)
# going to the same row
if p[0] > b[0]:
path += ["DOWN" for x in range(p[0]-b[0])]
elif p[0] < b [0]:
path += ["UP" for x in range(b[0]-p[0])]
# going to the same column
if p[1] > b[1]:
path += ["RIGHT" for x in range(p[1]-b[1])]
elif p[1] < b [1]:
path += ["LEFT" for x in range(b[1]-p[1])]
for action in path:
print(action)
m = int(input())
grid = []
for i in range(0, m):
grid.append(input().strip())
displayPathtoPrincess(m,grid)
|
#!/usr/bin/env python3
from random import randint, choice
from ships import *
import sys
from time import sleep
#Text to help the player with the how-to of the game
def ui():
"""Includes How-to-play of the original board game.
Just some stuff to be printed. Not much!"""
print("Hello!")
print("-------------Welcome to Battleships--------------")
print(
""""Instructions:
1) You have to place your ships on a 10*10 square as you like
and your opponent will do the same.
2) Both the players have 5 ships of various lengths. You have to guess
where the other person's ships are and if you guess correctly, you inflict
damage to the opponents ship.
3) First one to destroy other's ships wins!"""
)
print("-------------Various ships-------------------")
print(
"""
1) Carrier <----- size 5,
2) Battleship <---- size 4,
3) Destroyer <--- size 3,
4) Submarine <--- size 3,
5) Patrol Boat <-- size 2
"""
)
return 0
# Display the map
def show_grid(lst):
"""Shows the grid on the screen"""
print("\nPlacement of the ships\n")
print(" 0 1 2 3 4 5 6 7 8 9\n")
for index, x in enumerate(lst):
print(str(index), " ".join(map(str, x)), sep=" ")
return 0
# List of all the ships and their size
list_ships = [
("Carrier", 5),
("Battleship", 4),
("Destroyer", 3),
("Submarine", 3),
("Patrol Boat", 2)
]
# Generates a 10*10 grid
def load_grid():
"""Creates a 10*10 grid for use later in the other functions"""
lst = []
for x in range(10):
lst.append(['-','-','-','-','-','-','-','-','-','-'])
return lst
# Player Interaction
def player(show):
"""UI for the input from the player for the co-ordinates of the ships"""
print("-------------Let's begin then-------------------\n")
print("This is how the 10*10 grid looks\n")
lst = load_grid()
grid_with_zero(lst)
print("\nNow it is you turn to play:\n")
p = Player(input("Enter your name:"))
print("\nTry not to place the ships on the same place\n")
for ship, size in list_ships:
print(f"\nLet's place {ship} of size: {size}\n")
s = Ships(ship, size)
ship_placed = False
while not ship_placed:
r = int(input("Choose a value between 0-9 to choose the row:"))
c = int(input("Choose a value between 0-9 to choose a column:"))
o = input("Place horizontal(h) or vertical(v)?")
if o == 'h':
if c + s.size <= 9:
s.set_pos(r,r,c, c+s.size)
for grid_col in range(s.size):
lst[r][c] = 1
p.ship_coordinates.append((r,c))
c+=1
ship_placed = True
else:
print("The size of the ship is too big, try again!")
elif o == 'v':
if r + s.size <= 9:
s.set_pos(r,r+s.size, c,c)
for grid_row in lst[r:r+s.size]:
grid_row[c] = 1
p.ship_coordinates.append((r,c))
ship_placed = True
else:
print("The size of the ship is too big, try again!")
else:
print("Enter h or v for horizontal or vertical")
p.dict_ships[ship] = s
if show == 1:
show_grid(lst)
return p
# Generating values for computer ships
def comp(name, show):
"""Generates coordinates for the computer's ships"""
print(f"\nWaiting for {name} to place their ships\n")
sleep(1)
lst = load_grid()
p = Player(name)
for ship, size in list_ships:
s = Ships(ship, size)
ship_placed = False
while not ship_placed:
r = randint(0,9)
c = randint(0,9)
o = choice(['h','o'])
if o == 'h':
if c + s.size <= 9:
s.set_pos(r,r,c, c+s.size)
for grid_col in range(s.size):
lst[r][c] = 1
p.ship_coordinates.append((r,c))
c+=1
ship_placed = True
else:
continue
else:
if r + s.size <= 9:
s.set_pos(r,r+s.size, c,c)
for grid_row in lst[r:r+s.size]:
grid_row[c] = 1
p.ship_coordinates.append((r,c))
ship_placed = True
else:
continue
p.dict_ships[ship] = s
if show == 1:
show_grid(lst)
sleep(1)
return p
# Playing the game
def game(p1, p2):
"""This is where the actual gameplay resides"""
win = False
damage1 = 0
damage2 = 0
print("\nNow that both the players have their ships positioned, let's battle!\n")
while not win:
# Player1 or the human
# x,y = map(int, input("Enter x,y coordinates").split())
# if x in range(10) and y in range(10):
# if (x,y) in p2.ship_coordinates:
# print("Well done, That's a hit!")
# p2.ship_coordinates.remove((x,y))
# else:
# print("That was a miss. Better luch next time.")
x,y = randint(0,9), randint(0,9)
if (x,y) in p2.ship_coordinates:
# print("Hit! Your damaged opponent's ship.")
damage1 += 1
p2.ship_coordinates.remove((x,y))
else:
# print("Miss! Better luck next time.")
pass
u,v = randint(0,9), randint(0,9)
if (u,v) in p1.ship_coordinates:
# print("Computer hit. Your ship was damaged.")
damage2 += 1
p1.ship_coordinates.remove((u,v))
else:
# print("Miss! Your ship didn't get damaged.")
pass
if not p1.ship_coordinates:
print(f"{p2.player_name} won!")
break
elif not p2.ship_coordinates:
print(f"{p1.player_name} won!")
break
return damage1, damage2
# Call the necessary functions
if __name__ == '__main__':
if len(sys.argv) <= 4:
if len(sys.argv) > 1:
show, p1, p2 = sys.argv[1:]
else:
show, p1, p2 = 0, "Player1", "Player2"
else:
raise Exception("The max allowed number of arguments is 3")
player1 = comp(p1, int(show))
player2 = comp(p2, int(show))
hits = game(player1, player2)
sleep(1)
print(f"\n{player1.player_name} hit {hits[0]} and {player2.player_name} hit {hits[1]}")
|
#!/usr/bin/env python3
import sys
import math
from common import print_solution, read_input
def distance(city1, city2):
return math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2)
def solve(cities):
N = len(cities)
dist = [[0] * N for i in range(N)]
for i in range(N):
for j in range(N):
dist[i][j] = dist[j][i] = distance(cities[i], cities[j])
current_city = 0
unvisited_cities = set(range(1, N))
solution = [current_city]
def distance_from_current_city(to):
return dist[current_city][to]
while unvisited_cities:
next_city = min(unvisited_cities, key=distance_from_current_city)
unvisited_cities.remove(next_city)
solution.append(next_city)
current_city = next_city
return solution
if __name__ == '__main__':
assert len(sys.argv) > 1
solution = solve(read_input(sys.argv[1]))
print_solution(solution)
|
import pandas as pd
import json
from pymongo import MongoClient
def write_in_mongodb(dataframe, mongo_host, mongo_port, db_name, collection):
"""
:param dataframe:
:param mongo_host: Mongodb server address
:param mongo_port: Mongodb server port number
:param db_name: The name of the database
:param collection: the name of the collection inside the database
"""
client = MongoClient(host=mongo_host, port=mongo_port)
db = client[db_name]
c = db[collection]
# You can only store documents in mongodb;
# so you need to convert rows inside the dataframe into a list of json objects
records = json.loads(dataframe.T.to_json()).values()
c.insert_many(records)
def read_from_mongodb(mongo_host, mongo_port, db_name, collection):
"""
:param mongo_host: Mongodb server address
:param mongo_port: Mongodb server port number
:param db_name: The name of the database
:param collection: the name of the collection inside the database
:return: A dataframe which contains all documents inside the collection
"""
client = MongoClient(host=mongo_host, port=mongo_port)
db = client[db_name]
c = db[collection]
return pd.DataFrame(list(c.find()))
def print_dataframe(dataframe):
print(','.join(column for column in dataframe))
for index, row in dataframe.iterrows():
print(','.join(str(row[column] for column in dataframe)))
if __name__=='__main__':
db_name = 'comp9321'
mongo_port = 27017
mongo_host = 'localhost'
dataframe = pd.read_csv("Demographic Statistics.csv")
collection = 'Demographic_Statistics'
write_in_mongodb(dataframe, mongo_host, mongo_port, db_name, collection)
df = read_from_mongodb(mongo_host, mongo_port, db_name, collection)
print_dataframe(df)
|
import pandas as pd
import requests
def fetch(url):
params = dict(
origin='Chicago,IL',
destination='Los+Angeles,CA',
waypoints='Joplin,MO|Oklahoma+City,OK',
sensor='false'
)
resp = requests.get(url=url, params=params)
data = resp.json()
return data
def json_to_dataframe(json_obj):
json_data = json_obj['data']
print(json_data)
columns = []
for c in json_obj['meta']['view']['columns']:
columns.append(c['name'])
return pd.DataFrame(data=json_data, columns=columns)
def print_dataframe(dataframe):
print(",".join(coloumn for coloumn in dataframe))
for index, row in dataframe.iterrows():
print(",".join([str(row[column]) for column in dataframe]))
if __name__=='__main__':
csv_file = 'Demographic Statistics.csv'
dataframe = pd.read_csv(csv_file)
#fetch the url
url = "https://data.cityofnewyork.us/api/views/kku6-nxdu/rows.json"
json_obj = fetch(url)
dataframe = json_to_dataframe(json_obj)
#print_dataframe(dataframe) |
import matplotlib.pyplot as plt
import numpy as np
import math
def love7():
x = np.linspace(-2, 2, 1000)
f = np.sqrt(2 * np.sqrt(x * x) - x * x)
g = -1 * 2.14 * np.sqrt(math.sqrt(2) - np.sqrt(np.abs(x)))
plt.plot(x, f, color='red', linewidth=2)
plt.plot(x, g, color='red', linewidth=2)
plt.title('LOVE')
plt.legend()
plt.show()
if __name__ == '__main__':
love7()
|
# Online Python compiler (interpreter) to run Python online.
# Write Python 3 code in this online editor and run it.
#22/9/20
import datetime
x = datetime.datetime.now().strftime("%y")
xi = datetime.datetime.now().month
print(x)
print(xi)
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
print(next(myit))
print(next(myit))
li=[1,2,2]
lis=[]
for x in li:
lis.append(x**2)
print(lis)
lis2=(list(map(lambda x: x**2,li)))
print(lis2)
sz=1+2
def Display(zi,zii):
z=zii+zi
print(z)
def main():
Display(10,2)
return 2
main()
##
import math
import os
import random
import re
import sys
if __name__ == '__main__':
N = int(input().strip())
for i in range(1, 10 + 1):
print (N, "x", i, "=", N*i)
|
from turtle import *
from random import random
from freegames import line
def draw():
"Draw maze."
color('black')
width(5)
for x in range(-200,200,40):
for y in range(-200,200,40):
if random() > 0.5:
line(x,y, x + 40 ,y + 40)
else:
line(x,y+40, x+40 , y)
update()
def tap():
"Draw line and dot fro screen tap"
if abs(x) > 198 or abs(y) > 198:
up()
else:
down()
width(20)
color('red')
goto(x, y)
dot(4)
setup(420,420,370,0)
hideturtle()
tracer(False)
draw()
onscreenclick(tap)
done()
|
class myclass():
def __str__(self):
return "4"
print(myclass())
def my_function(fname,lname):
print(fname + lname+" Refsnes")
my_function("Emil","ee")
my_function("Emiel","ee")
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
|
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 25 16:53:41 2018
@author: root
"""
"""
animate the contour of a field in a surface.
input:
*field*: the field you want to animate
*extension*: the slice surface you want to animate
*proc*: the processor number that slices data from
*filename*: the name of the generated video
output:
a video: which shows the animation of slices,
locates in the current directory
# =============================================================================
# call signature: slicesAnimate(field='bb1', extension='xy', proc=0,
filename='bb1_xy.mp4')
# =============================================================================
# =============================================================================
# attention: close the animation figure to get out the function
# =============================================================================
"""
def slicesAnimate(*args, **kwargs):
animate_temp = __SlicesAnimate__(*args, **kwargs)
animate_temp.__read__()
animate_temp.__animate__()
return animate_temp
class __SlicesAnimate__(object):
def __init__(self, field='bb1', extension='xy', proc=-1, filename=None):
self.field = field
self.extension = extension
self.proc = proc
if(filename == None):
self.filename = field+'_'+extension+'.mp4'
def __read__(self):
from ..read import slices, grid
self.slices = slices(field=self.field,extension=self.extension, proc=self.proc)
self.grid = grid(proc=self.proc,trim=True) # 坐标的数值分割
def __animate__(self):
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
ax = fig.gca()
#title = plt.title()
#ax.contourf(self.slice_data[0,:,:],cmap='plasma')
X,Y = np.meshgrid(self.grid.x, self.grid.y)
Z = getattr(getattr(self.slices, self.extension), self.field)
# def init():
# frame.set_data([self.slice_data[0,:,:]])
# #title
# return frame,
#
def updatefig(i):
ax.clear()
ax.contourf(X, Y, Z[i,:,:],cmap='plasma')
ax.set_aspect(1)
#frame.set_data(self.slice_data[i,:,:])
ax.set_title('t = %f' % self.slices.t[i] )
return ax
ani = animation.FuncAnimation(fig, updatefig,len(self.slices.t), interval=50, blit=False)
ani.save(self.filename,fps=5,dpi=80, writer='ffmpeg')
plt.show()
|
import sys
def reverse_txt(file_name):
f = open(file_name, "r")
lines = f.readlines()
f.close()
f = open(file_name, "a")
for i in range(len(lines) - 1, -1, -1):
f.write(lines[i])
f.close()
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python3 reverse_txt.py <txt_file>")
else:
file = sys.argv[1]
reverse_txt(file)
|
"""
To evaluate the good or bad score of a tweet, we first tokenize the tweet, and then
stemmize each word in our tweet. We also associate each stem with positive and negative values,
respectively, using a dictionary.
Finally, we caculate the average word weight of a tweet, and decide if it's a good or bad one
based on that.
"""
import json
import html
import twitter
import time
from nltk import word_tokenize, pos_tag
from nltk.stem.porter import *
# Split a tweet string into words METHOD
def get_words(str):
useful_pos = {'NN'}
tokens = word_tokenize(str)
tags = pos_tag(tokens)
return [word for word, pos in tags if pos in useful_pos]
missing_words = {}
# Calculate the average value of words in list_of_words METHOD
def get_average_word_weight(list_of_words, word_weights):
number_of_words = len(list_of_words)
sum_of_word_weights = 0.0
print (number_of_words)
if number_of_words == 0:
return 0.0
stemmer = PorterStemmer()
# Interate through the words in the tweet string
for w in list_of_words:
stemmed_word = stemmer.stem(w)
if stemmed_word in word_weights:
sum_of_word_weights += word_weights[stemmed_word]
else:
missing_words[stemmed_word] = 0.0
return sum_of_word_weights / number_of_words
def analyse_tweet(tweet_string, word_weights):
words = get_words(tweet_string)
avg_tweet_weight = get_average_word_weight(words, word_weights)
print (tweet_string + ":" + str(avg_tweet_weight))
# Read tweets from an outside source
def load_json(json_file):
with open(json_file) as f:
return json.load(f)
word_weights = load_json("word_weights.json")
credentials = load_json(".cred.json")
api = twitter.Api(consumer_key=credentials["consumer_key"],
consumer_secret=credentials["consumer_secret"],
access_token_key=credentials["access_token_key"],
access_token_secret=credentials["access_token_secret"],
tweet_mode='extended')
# Load the last 10 status updates of Donald Trump
statuses = api.GetUserTimeline(screen_name="realDonaldTrump", count=10)
for status in statuses:
analyse_tweet(html.unescape(status.full_text), word_weights)
prev_status = status.full_text
print (missing_words)
|
"""
1. Requirement: Create an API Service to fetch the statistics of the contributors of user specified GitHub repositories
in the Amazon Web Services Environment.
2. Identify and list unique domains to the specified repository and sort them by the number of commits per contributor
for all the branches.
3. The Repository name and Date are the parameters to be passed for the REST API to fetch the contributor data.
4. Create a table in AWS Relational Database Service SQL instance for storing the data pertaining to the fields Unique
ID, Repo Name, Domain Name, Count, Date range parameter, Date of Run collected using API.
"""
# Importing Necessary Packages/Libraries
import requests
import pandas as pd
import pymysql
from datetime import date, datetime
Start_Time = datetime.now()
# Input - GitHub Username & Date Range
# Repo_Name = input("Enter the GitHub Repository Name (Username/Repo Name):- ")
# Start_Date = input("Enter the Start Date (YYYY-MM-DD):- ")
# End_Date = input("Enter the End Date (YYYY-MM-DD):- ")
# Pre-Input Data
Repo_Name = 'hashicorp/consul' # Repository Name
Start_Date = '2021-07-01' # Start Date of Range
End_Date = '2021-08-13' # End Date of Range
Auth = {'Authorization': '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'} # Authorization Token
Run_Date = date.today() # Run_Date to get today's date
Data_Frame = pd.DataFrame() # Creating Pandas DataFrame to store in the data
Output_Json = {} # Output_Json will contain the main output of the code
Length_Sum = 0 # To keep the count of the Total Contributions made
Unique_Sum = 0 # To keep the count of the Unique Contributors
Page_Number = 1 # Page_Number for getting requests from more than 1 page
# Fetching the JSON Data from the API
while True:
# URL to which the Request will be sent to fetch the details of the Commits and all other stuffs
url = f"https://api.github.com/repos/{Repo_Name}/commits?page={Page_Number}&since={Start_Date}&until={End_Date}"
# Getting the request
Request = requests.get(url, Auth).json()
# Taking the length of the request received
Length = len(Request)
# 'Length_Sum' analyse us with the Total Contribution made within the given Date Range
Length_Sum += Length
# Checking if the request was received or not
if Request:
# Concatenating the JSON Data into the 'Data_Frame' and re-setting its Index
Data_Frame = pd.concat([Data_Frame, pd.DataFrame(Request)], ignore_index=True)
# Incrementing the 'Page_Number'
Page_Number = Page_Number + 1
else:
# If no 'Request' has been received then it will run the following and break the loop and exit it
# URL to which the Request will be sent to fetch the Languages
url = f"https://api.github.com/repos/{Repo_Name}/languages"
# Getting the request
Response = requests.get(url, Auth).json()
Total_Bytes = 0 # To keep the count of the Total Bytes
# Calculating the Total Bytes
for x in Response:
Total_Bytes += Response[x]
# Calculating the Percentage
for x in Response:
# Calculating the Percentage and rounding of to 2 places
Percentage = round((Response[x] / Total_Bytes * 100), 2)
Response[x] = f'{Percentage}%'
break
New_Data_Frame = Data_Frame # Copying it to New DataFrame
# Processing the JSON Data Received from the API
for Request in New_Data_Frame['commit']:
Email_Id = Request['author']['email'] # Taking the Email Id of the Author
Email_End = Email_Id.split('@') # Splitting the Email Id into Username and Domain Name
Company = Email_End[1].rsplit('.', 1) # Splitting the Domain Name into the Company Name and the Extension
Company_Name = Company[0] # Storing the Company Initial Name
Full_Date = Request['author']['date'] # Taking the Date and Time when the commit took place
Only_Date = Full_Date.split('T') # Splitting the Full_Date into Date and the Time
Date = Only_Date[0] # Storing the Date only
# Loop for Processing the Total Contributions
if Company_Name in Output_Json.keys():
# If the 'Company_Name' is already present then it will increment the 'Total Contributions' by 1
Output_Json[Company_Name]['Total Contributions'] = Output_Json[Company_Name]['Total Contributions'] + 1
else:
# If the 'Company_Name' is not present then it will assign the 'Total Contributions' to 1
Output_Json[Company_Name] = {'Total Contributions': 1, 'Unique Contributors': 0, 'Users': [], 'Date': []}
# Loop for Processing the Unique Contributors
# If the particular 'Email_Id' is already present then the loop won't run, whereas if it's not present then the loop will run
if Email_Id not in Output_Json[Company_Name]['Users']:
# Adding the Users Email_Id inorder to make the 'Unique Contributors'
Output_Json[Company_Name]['Users'].append(Email_Id)
# Incrementing the 'Unique Contributors' by 1
Output_Json[Company_Name]['Unique Contributors'] = Output_Json[Company_Name]['Unique Contributors'] + 1
# 'Unique_Sum' analyse us with the Total Unique Contributors who made commits within the given Date Range
Unique_Sum += 1
# Loop for Processing the Commit Date
if Date not in Output_Json[Company_Name]['Date']:
Output_Json[Company_Name]['Date'].append(Date)
# Output - Company Domain Name, Total number of Commits & Total number of Contributors
print(f'Total Companies:- {len(Output_Json)}-{list(Output_Json.keys())}') # Printing the Domain/Companies name
print(f'Total Contributions:- {Length_Sum}') # Printing the Count of Total Contributions made
print(f'Unique Contributors:- {Unique_Sum}') # Printing the Count of Unique Contributors who have contributed
print(f'Languages Used:- {Response}') # Printing the Languages
print(f'Output:- {Output_Json}') # Printing the Required Json Data
# Loop for Storing the data into Database
# Establishing the connection/Connecting to the Database
connection = pymysql.connect(host="localhost", user="root", password="", database="mydb")
cur = connection.cursor()
# Query for Fetching the last 'UNIQUE_ID' from the Database
cur.execute("SELECT UNIQUE_ID FROM mydb.GitHub ORDER BY UNIQUE_ID DESC LIMIT 1;")
Unique_Id = cur.fetchall()
# Loop for Checking whether the Unique_Id is empty or not
if not Unique_Id:
Unique_Id = 0
else:
Unique_Id = int(Unique_Id[0][0])
for x in Output_Json:
Unique_Id = Unique_Id + 1
# Query for Inserting into Database
cur.execute("INSERT INTO mydb.GitHub (UNIQUE_ID, REPO_NAME, DOMAIN_NAME, TOTAL_CONTRI, UNIQUE_CONTRI, COMMIT_DATE, DATE_OF_RUN) VALUES (%s,%s,%s,%s,%s,%s,%s)",
(str(Unique_Id), str(Repo_Name), str(x), str(Output_Json[x]['Total Contributions']), str(Output_Json[x]['Unique Contributors']), str(Output_Json[x]['Date']), str(Run_Date)))
# Committing the changes in the Database
connection.commit()
End_Time = datetime.now()
print(f'Execution Time:- {End_Time - Start_Time}') # Printing the Execution Time
"""
Input : Repository name
Output: Company domain name, along with total number of commits and total number of contributors
Input: hashicorp/consul
Output should be: { "microsoft": { Total Contributions: 50, Unique Contributors: 10 }
"hashicorp": {Total Contributions: 15, Unique Contributors: 12 } , "gmail": { Total Contributions: 50,
Unique Contributors: 11 } , "cloudflare": { Total Contributions: 52, Unique Contributors: 10 } }
"""
|
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# li1 = [1,2,3]
# print(li1)
#
# li2 = ["a", "sdf", li1, [6,7,8]]
# print(li2)
#
# li2[0]
#
# li2.append("world")
# print(li2)
#
# li2.remove("sdf")
# print(li2)
#
# del li2[0]
# print(li2)
#
# li1
# del li1
# #li1
#
# li1 = [1,2,3]
# li1
# li1.clear() #清空列表,列表为空但是仍存在
# li1
# #list1 = [1, 2, 3, 4, 5]
# list1 = [[1,2],3,4,[5,6,7]]
# print(type(list1))
# print(type(list1[0]))
# for i in list1:
# if type(i) == list:
# for j in i:
# print(j)
# else:
# print(i)
#列表反转
# list2 = [1, 2, 3, 4, 5]
# list2.reverse()
# print(list2)
# print(list2[::-1]) #反转
# 冒泡排序:最小数往下沉
# list1 = [1, 45, 3, 7, 2]
# for i in range(0, len(list1)-1):# 外层循环len(list1)-1次
# for j in range(0, len(list1)-i-1):#内层循环i+j=len(list1)-1
# if list1[j] < list1[j+1]:
# list1[j], list1[j+1] = list1[j+1], list1[j]
# print(list1)
#两种for循环是不一样的
# for i in list (i代表数据元素)
# for i in range(0, len(list)-1) (i代表的是下标)
list1 = [1001, 123, 1000]
list1.sort()
|
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# author:Administrator
# datetime:2018/12/16 9:33
# software: PyCharm
import socket
class ClientSocket:
def __init__(self):
self.client = socket.socket()
def conn_server(self):
# self.client.connect(('192.168.2.125',8888))
self.client.connect(('127.0.0.1', 8888))
# 接收从服务端来的欢迎消息
welcome_info = self.client.recv(1024).decode()
print(welcome_info)
self.send_receive()
def send_receive(self):
while 1:
msg = input('请输入您要说的话:')
#如果没有输入quit,就进行消息发送
if msg != 'quit':
# 发送消息至服务器
self.client.send(msg.encode())
# 接收从服务器的反馈
confirm_msg = self.client.recv(1024).decode()
print(confirm_msg)
else:
choice = input('您真的要退出吗?(y/n)')
if choice.lower() == 'y':
self.client.send('y'.encode())
print('您退出了蜗牛聊天室')
break
def __del__(self):
self.client.close()
if __name__ == '__main__':
ClientSocket().conn_server()
|
# TODO
# 1. Create a list of "person" dictionaries with a name, age, and list of hobbies for each one <**DONE**>
# 2. Use a list comprehension to convert this list of persons into a list of names (of the persons) <**DONE**>
# 3. Use a list comprehension to check whether all persons are older than twenty <**DONE**>
# 4. Copy the person list such that you can safely edit the name of the first person (without changing) the original list <**DONE**>
# 5. Upack the persons of the original list into different variables and output these VARIABLES <**DONE**>
eugene = {'name': 'Eugene', 'age':30, 'hobbies':['reading', 'writing', 'rithmatic']}
frank = {'name': 'Frank', 'age': 85, 'hobbies': ['napping', 'doing pushups', 'brawling']}
sally = {'name': 'Sally', 'age': 15, 'hobbies': ['cutting class', 'running a small business', 'not sleeping']}
persons = [eugene, frank, sally]
names = []
over_20 = []
n = len(names)
def list_names():
for person in persons:
names.append(person['name'])
print(names)
def age_check():
for person in persons:
if person['age'] > 20:
over_20.append(person['age'])
print(over_20)
def copy_names():
list_names()
dup_names = names[:]
dup_names[0] = 'Gene'
print(names)
print(dup_names)
def unpack_names():
name_1, name_2, name_3 = names
print(name_1)
print(name_2)
print(name_3)
copy_names()
age_check()
unpack_names()
|
"""
Algorithms.py
====================================
Module containing all graph algo i use in my Graph-rendering project
"""
import collections
from typing import Optional
from graph.Graph import Graph
from graph import GifMaker
def graph_pass_and_gif(graph: Graph, node: int, method, draw=False) -> list:
"""
:param graph: graph: class object: The graph in which to run method
:param node: int: index of starting node
:param method: function: method what used for visualisation
:param draw: bool: Make step files during graph_pass_and_gif creation
:return: list(imageio.class): result of imageio working with graph steps during method run
"""
path = method(graph, node)
gif_img = GifMaker.build_from_graph(graph, path, draw)
return gif_img
def DFS(graph: Graph, node: int) -> set:
"""
:param graph: class object: The graph in which to run DFS
:param node: int: index of starting node
:return: visited: list: index of visited nodes, basically path
"""
return __DFS(graph, node, set())
def __DFS(graph: Graph, node: int, visited: set) -> set:
"""
:param graph: class object: The graph in which to run DFS
:param visited: list: Numbers of visited nodes, basically path
:param node: int: number of the current node
:return visited: set: Numbers of visited nodes, basically path
"""
if node not in visited:
visited.add(node)
for neighbour in graph.adjacency_list[node]:
visited = __DFS(graph, neighbour, visited=visited)
return visited
def BFS(graph: Graph, node: int) -> set:
"""
:param graph: class object: The graph in which to run BFS
:param node: int: number of node from we run BFS
:return: set[] path
"""
visited = {node}
path = {node}
queue = collections.deque([node]) # We put the current vertex, and the current color
while queue:
vertex = queue.popleft()
for neighbour in graph.adjacency_list[vertex]:
if neighbour not in visited:
visited.add(neighbour)
path.add(neighbour) # Remember that we were here
queue.append(neighbour) # Adding a neighbor to then walk out of it
return path
|
#################
#
# get_program_version
# written by: Andy Block
# date: Jan 3, 2021
#
#################
#
# this program simply prints out the version number of a given Windows executable.
# the only argument required is the file path of the exexcutable you want the version of.
#
# for example, the file path for chrome.exe at its default location is:
# filepath = 'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'
#
# there are two different versions in Windows: the file version and the product version.
# usually these two values are equivalent, and if so, the program only prints one value.
# if they are not equal, both will be printed.
#
#################
from win32api import GetFileVersionInfo, HIWORD, LOWORD
def get_program_version(filepath, print_ver=False):
info = GetFileVersionInfo(filepath, '\\')
file_version = str(HIWORD(info['FileVersionMS'])) + '.' + \
str(LOWORD(info['FileVersionMS'])) + '.' + \
str(HIWORD(info['FileVersionLS'])) + '.' + \
str(LOWORD(info['FileVersionLS']))
product_version = str(HIWORD(info['ProductVersionMS'])) + '.' + \
str(LOWORD(info['ProductVersionMS'])) + '.' + \
str(HIWORD(info['ProductVersionLS'])) + '.' + \
str(LOWORD(info['ProductVersionLS']))
if print_ver == True:
if file_version == product_version:
print("This program's version is: " + file_version)
else:
print("This program's file version is: " + file_version)
print("This program's product version is: " + product_version)
return file_version, product_version |
# practice 4
user_input = int(input("Enter a number:"))
i = 0
for i in range(user_input):
i = user_input*2
user_input += user_input
print(i)
|
#Problem: Extracting data from XML
#visit this url for the problem - https://www.py4e.com/tools/python-data/?PHPSESSID=f2d57a1839533b3bf8e7129dcb08d0e0
import urllib.request, urllib.parse, urllib.error
import xml.etree.ElementTree as ET
input_url = input('enter URL - ')
data = urllib.request.urlopen(input_url).read()
tree = ET.fromstring(data)
counts = tree.findall('comments/comment/count')
sum = 0
for count in counts:
sum = sum + int(count.text)
print(sum)
|
a=input("enter a string to reverse : ")
revs=""
for s in a:
revs=s+revs
print(revs) |
a=[1,3,2,4,5,6,5,8]
import collections
print([item for item, count in collections.Counter(a).items() if count > 1])
|
import random
import math
class Electric:
def __init__(self, name):
self.name = name
class Load(Electric):
def __init__(self, name, resistance, reactance):
super().__init__(name)
self.resistance = resistance
self.reactance = reactance
self.__n = (random.randint(1, 100) / 100)
def current_load(self, voltage):
self.__current = voltage / math.sqrt((self.resistance ** 2) + (self.reactance ** 2))
print(f'The current at {voltage}Volt is {round(self.__current, 3)}Amper')
return self.__current
class Generator(Electric):
def __init__(self, name, power, voltage):
super().__init__(name)
self.power = power
self.voltage = voltage
def load_capacity(self, load_c):
if (self.voltage * load_c) > self.power:
print('Generator overloaded, expect trouble')
else:
print('System working properly')
load1 = Load('address#1', 10, 2)
gen1 = Generator('kuciurgan', 10000, 220)
print(f'The load at {load1.name} has R = {load1.resistance} and X = {load1.reactance}')
print(f'The generator at {gen1.name} gives {gen1.power}VA and stable {gen1.voltage}V')
gen1.load_capacity(load1.current_load(gen1.voltage))
|
# Permutations
# Given a collection of numbers, return all possible permutations.
# For example,
# [1,2,3] have the following permutations:
# [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
class Premu:
dlist = [1,2,3]
vlist = [0,0,0]
rlist = []
def __init__(self):
pass
def __del__(self):
pass
def per(self,level):
size = len(self.dlist)
if(level == size):
print(self.rlist)
for index in range(0,size):
if 0 == self.vlist[index]:
self.vlist[index] = 1
self.rlist.append(self.dlist[index])
self.per(level + 1)
self.rlist.pop(len(self.rlist) -1)
self.vlist[index] = 0
test = Premu()
test.per(0)
|
# File Name: days_in_month.py
# Name: Kit Wei Min
# Description: Displays the number of days in the month of a year entered by the user.
# Prompts user to input the month and year.
yr = int(input("Enter a year: "))
mth = int(input("Enter the month: "))
# Determines the number of days in the month of the year entered and displays the result.
if mth == 1:
print("January " + str(yr) + " has 31 days.")
elif mth == 2:
if yr % 4 == 0 and yr % 100 != 0 or yr % 400 == 0:
print("February " + str(yr) + " has 29 days.")
else:
print("February " + str(yr) + " has 28 days.")
elif mth == 3:
print("March " + str(yr) + " has 31 days.")
elif mth == 4:
print("April" + str(yr) + "has 30 days.")
elif mth == 5:
print("May " + str(yr) + " has 31 days.")
elif mth == 6:
print("June " + str(yr) + "has 30 days.")
elif mth == 7:
print("July" , yr , "has 31 days.")
elif mth == 8:
print("August" , yr , "has 31 days.")
elif mth == 9:
print("September" , yr , "has 30 days.")
elif mth == 10:
print("October" , yr , "has 31 days.")
elif mth == 11:
print("November" , yr , "has 30 days.")
elif mth == 12:
print("December" , yr , "has 31 days.")
|
# Filename : ASCII_character
# Name : Kit Wei Min
# Description : Displays the character of an ASCII code.
# Prompts for an ASCII code
code = int(input("Enter ASCII code (between 0-127 exclusive): "))
# Converts ASCII code
character = chr(code)
print("Character of code: " "{0}". format(character))
|
#!/usr/bin/python
import sys
from datetime import datetime
COLOURS = [1,2,3,4,5,6,7]
class rainbow:
"""
The rainbow class provides static, scrolling or pulsating rainbow
colouring of text. Exports pulsebar() and scrollbar().
"""
odd = speed = colidx = lasttime = -1
def __init__(self, fps=10):
"""Initiate speed based on fps."""
onesecond = 1000000
self.speed = onesecond / fps
def pulsebar(self, text):
"""Write the text in the colour of the current time frame."""
time = int(datetime.now().strftime("%f")) / self.speed
sys.stdout.write("\033[0;3%dm%s\033[0m" % (COLOURS[time % len(COLOURS)], text))
#sys.stdout.flush()
def scrollbar(self, text, colourlen=8):
"""
Write the text in colours specified by the current time frame.
The text is coloured in columns of colourlen characters.
"""
pos = i = 0
textlen = len(text)
if self.colidx < 0:
self.colidx = 0
if colourlen < 1:
colourlen = 1
if self.odd < 0:
self.odd = colourlen - 1;
now = datetime.now().strftime("%S%f")
time = int(now[:2]) * 1000000 + int(now[2:])
if abs(self.lasttime - time) >= self.speed:
self.odd = (self.odd + 1) % colourlen
self.lasttime = time
if self.odd == 0:
self.colidx = len(COLOURS) - 1 if self.colidx == 0 else self.colidx - 1
while pos < self.odd and pos < textlen:
sys.stdout.write("\033[0;3%dm%c\033[0m" % (COLOURS[self.colidx % len(COLOURS)], text[pos]))
pos += 1
while pos < textlen:
sys.stdout.write("\033[0;3%dm%c\033[0m" % (COLOURS[(self.colidx + 1 + i / colourlen) % len(COLOURS)], text[pos]))
pos += 1
i += 1
sys.stdout.write("\033[0m");
#sys.stdout.flush()
if __name__ == "__main__":
"""Write the input text coloured in columns of argv[1] (or 3) characters."""
if(len(sys.argv) > 1 and sys.argv[1] == '-v'):
print 'Usage:'
print ' ' + sys.argv[0] + ' [duration]'
print ' ' + sys.argv[0] + ' -h'
sys.exit(0)
r = rainbow(1)
while True:
colourlen = int(sys.argv[1]) if len(sys.argv) > 1 else 3
strs = file.read(sys.stdin).splitlines()
for s in strs:
r.scrollbar(s, colourlen)
sys.stdout.write('\n')
sys.exit(0)
|
#Desenvolva um programa que pergunte a distancia de uma viagem em KM.
#Calcule o preço da passagem, cobrando R$0,50 por km para viagens de ate 200 Km
# e R$0,45 para viagens mais longas.
dist = float(input('Qual a distancia em Kilometros até o seu destino? '))
if dist <= 200.00:
d1 = dist * 0.50
print(f'O valor da sua passagem será de R${d1:.2f} ')
else:
d1 = dist * 0.45
print(f'O valor da sua passagem será de R${d1:.2f} ')
|
#Crie um programa que leia um numero real qualquer pelo teclado e mostre na tela a sua porção inteira
#ex: Digite um numero 6,127 "O numero 6,127 tem a parte inteira 6"
from math import trunc
num = float(input('Digite qualquer valor: '))
print(f'O valor de {num} tem como numero inteiro {trunc(num)} ')
|
#Crie um programa que leia o nome de uma pessoa e diga se ela tem "silva" no nome
name = str(input('Digite o seu nome completo? ')).strip().title()
n1 = name.split()
print(f'Seu nome completo é {name} e é {"Silva" in n1} que vc tem Silva no seu nome ')
|
users = [
{
'name': 'Rolf',
'age': 34
},
{
'name': 'Anna',
'age': 28
}
]
def print_users_list(user_list):
for i, user in enumerate(user_list):
print_user_details(i, user)
def print_user_details(number, user):
print("{} | name: {}, age: {}.".format(number, user['name'], user['age']))
print_user_list(users) |
# -*- coding: UTF-8 -*-
import numpy as np
from scipy.integrate import quad
# Funcion a integrar: cos²(e^x)
def f(x):
return np.cos(np.exp(x)) ** 2
# Integrar la función en los límites 0, 3
# quad devuelve un arreglo con 2 elementos: el primero, la solución
# el segundo, el error
solucion = quad(f, 0, 3)
print "La solución es: %s " % (str(solucion)) |
# -*- coding: utf-8 -*-
import pylab as pl
# Definición de funciones auxiliares
def f1(x):
return x**2
def f2(x):
return x**3
def f3(x):
return 1./x
def f4(x):
return pl.sqrt(x)
X = pl.arange(1,100)
fig = pl.figure("Varios plots")
# Vamos a crear un grid de 2x2 con 4 subplots
sp1 = fig.add_subplot(221, title='$f(x) = x^2$') # Ojo al titulo con expresión matemática
sp2 = fig.add_subplot(222, title='$f(x) = x^3$')
sp3 = fig.add_subplot(223, title= '$f(x) = \\frac{1}{x}$')
sp4 = fig.add_subplot(224, title = '$f(x) = \sqrt{x}$')
Y1 = f1(X)
Y2 = f2(X)
Y3 = f3(X)
Y4 = f4(X)
sp1.plot(X, Y1, color="red")
sp2.plot(X, Y2, color="blue")
sp3.plot(X, Y3, color="green")
sp4.plot(X, Y4, color="orange")
pl.show()
|
import pandas as pd
from sklearn.cluster import KMeans
def kmeans():
df = pd.read_csv('clusters.txt', names=['x','y'])
# initialize the KMeans class with the # of clusters
kmeans = KMeans(n_clusters=3)
kmeans.fit(df)
centroids = kmeans.cluster_centers_
print("Centroids:")
for i in centroids:
print("({}, {})".format(i[0], i[1]))
if __name__ == '__main__':
kmeans()
|
phone = input('Phone: ')
dict_phone = {
'1':'One','2':'Two','3':'Three','4':'Four','5':'Five',
'6':'Six','7':'Seven','8':'Eight','9':'Nine'
}
output = ""
for ch in phone:
output += dict_phone.get(ch,"!") + " "
print(output) |
#!/usr/bin/python2.5
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.corpus.reader import VERB
from nltk.corpus.reader import NOUN
from sys import stdin, argv
if len(argv) == 2:
splitby = eval(argv[1])
else:
splitby = '\t'
lemmatizer = WordNetLemmatizer()
#
# we assume the file is built of pos/word pairs, optionally followed by a number
#
for line in stdin:
words = line.rstrip().split(splitby)
poswords = list((words[2*i], words[2*i+1]) for i in range(len(words)/2))
append = []
for (pos, word) in poswords:
if pos.lower().startswith("v"):
append.append(lemmatizer.lemmatize(word, VERB))
elif pos.lower().startswith("n"):
append.append(lemmatizer.lemmatize(word, NOUN))
else:
append.append(word)
if len(words) > (len(words) / 2) * 2:
append.append(words[-1])
words = words[:-1]
print splitby.join(words + append)
|
# @author: Ashish Shetty aka AlphaSierra
# Fibonacci sequence generator my implementation
fibonacci_list = [0, 1]# List created with twi initial numbers hardcoded in it. Now ask user for input for ranging
last = int(input("Please input the limit of Fibonacci series you want to enlist: "))
def fib():# define fibonacci generator function
m = 0
n = 1
i = 0
for i in range(last):# for loop iterates "last" no of times and appends new fibonacci no. on each loop completion
p = m + n
m = n
n = p
fibonacci_list.append(p)
print(fibonacci_list)# once the loop iteration is done. The entire fibonacci sequence list is printed out
fib()# call the fib function
|
length=int(input("enter any length"))
breadth=int(input("enter of rectangle"))
if length==breadth:
print("it is square")
else:
print("it is not square") |
# Write a python program to enter two numbers and perform all arithmetic operations.
num1=int(input("enter a num1"))
num2=int(input("enter a num2"))
sum=num1+num2
sub=num1-num2
mul=num1*num2
divide=num1/num2
mod=num1%num2
print(sum,"num1+num2")
print(sub,"num1-num2")
print(mul,"num1*num2")
print(divide,"num/num2")
print(mod,"num1%num2")
|
girls=int(input("enter the girls ="))
bed=int(input("enter the bed ="))
if girls==bed:
print("bed girls is equal")
elif girls>bed:
print("bed is less",girls-bed)
else:
print("girls is more",bed-girls)
file=open("Q3.txt","a")
file.write("navgurukul is the best place for learning")
file.write('\n')
file.close()
file=open("Q3.txt","r")
print(file.read)
file.close() |
# Write a python program to calculate profit or loss.
cost_price=int(input("enter a cost price "))
selling_price=int(input("enter a seeling price"))
if cost_price>selling_price:
print("profit")
elif cost_price==selling_price:
print("no profit no loss")
else:
print("loss") |
def getminsteps(a):
steps=[0 for x in range(len(a))]
if(a[0]==0 or len(a)==0):
return(float('inf'))
for i in range(1,len(a)):
steps[i]=float('inf')
for j in range(i):
if((i<=j+a[j]) and (a[j]!=float('inf'))):
steps[i]=min(steps[i],steps[j]+1)
break
return(steps[-1])
a=[int(x) for x in input().split()]
print(getminsteps(a))
|
import math
def check(a,b):
ch=0
while(a%2==0):
ch+=1
if(ch==b):
return(2)
a=a//2
for i in range(3,int(math.sqrt(a))+1,2):
while(a%i==0):
ch+=1
if(ch==b):
return(i)
a=a//i
if(a>2):
ch+=1
if(ch==b):
return(a)
return(-1)
a,b=map(int,input().split())
print(check(a,b))
|
import math
def check(a):
out=[]
while(a%2==0):
out.append(2)
a=int(a//2)
for i in range(3,int(math.sqrt((a)))+1,2):
while(a%i==0):
out.append(i)
a=int(a//i)
if(a>2):
out.append(a)
print(*out,sep=" ")
a=int(input())
check(a)
|
import random
import time
class Game_2048():
""" This class represent gamegrid and function"""
def __init__(self):
""" Create new grid """
self.grid = [[0, 0, 0, 0], [0, 0, 0, 0],
[0, 0, 0, 0], [0, 0, 0, 0]]
self.score = 0
self.status = True
self.maxcell = 0
self.goal = 0
self.directions = ['z', 'q', 's', 'd']
def maxcell_find(self):
''' Identifies the value of the maximum cell self.grid'''
check = 0
for i in range(4):
for j in range(4):
if self.grid[i][j] > check:
check = self.grid[i][j]
self.maxcell = check
return self.maxcell
def sup_2048(self):
''' Counts the amount of cells with value
greater than or equal to 2048'''
count = 0
for i in range(4):
for j in range(4):
if self.grid[i][j] >= 2048:
count += 1
self.goal = count
return self.goal
def newcell_start(self):
''' Add new cell to the grid when grid is empty.
Probability are 1/10 to be a 4
9/10 to be a 2
see example:
grid [0, 0, 0, 0] Become [0, 0, 2, 0]
[0, 0, 0, 0] [0, 0, 0, 0]
[0, 0, 0, 0] [0, 0, 0, 0]
[0, 0, 0, 0] [0, 0, 0, 0]
'''
new_cell = 2
pos1 = random.randint(a=0, b=3)
pos2 = random.randint(a=0, b=3)
if random.uniform(a=0, b=1) > 0.90:
new_cell = 4
self.grid[pos1][pos2] = new_cell
return self.grid
def newcell(self):
''' Add new cell to the grid.
Probability are 1/10 to be a 4
9/10 to be a 2
see example:
grid [0, 2, 2, 0] Become [0, 2, 2, 0]
[0, 0, 0, 0] [0, 0, 0, 0]
[0, 0, 0, 0] [4, 0, 0, 0]
[0, 0, 0, 0] [0, 0, 0, 0]
'''
empty_cell = []
new_cell = 2
pos = (0, 0)
for i in range(4):
for j in range(4):
if (self.grid[i][j] == 0):
empty_cell.append((i, j))
if random.uniform(a=0, b=1) > 0.90:
new_cell = 4
todo = len(empty_cell)
if todo == 0:
todo += 1
pos = random.randint(a=0, b=todo-1)
if len(empty_cell) == 0:
pos = [0, 0]
else:
pos = empty_cell[pos]
a, b = pos[0], pos[1]
self.grid[a][b] = new_cell
return self.grid
def display(self):
''' Display grid and score.
see example:
[0, 2, 2, 4]
[0, 0, 4, 2]
[4, 0, 2, 2]
[8, 2, 4, 8]
Your score is 32
'''
print(self.grid[0])
print(self.grid[1])
print(self.grid[2])
print(self.grid[3])
print(f'Your score is {self.score}')
def possible_action(self):
'''Checks if a movement is possible on the grid
See example:
grid1 = [2, 4, 8, 4] grid2 = [8, 4, 8, 4]
[2, 8, 4, 8] [2, 8, 4, 8]
[4, 2, 8, 4] [4, 2, 8, 4]
[2, 4, 2, 8] [2, 4, 2, 8]
grid1[0][0] and grid1[1][0] can be merged. No two cells can be merged.'''
p_a = False
for i in range(3):
for j in range(3):
if(self.grid[i][j] == self.grid[i + 1][j] or self.grid[i][j] == self.grid[i][j + 1]):
p_a = True
for j in range(3):
if(self.grid[3][j] == self.grid[3][j + 1]):
p_a = True
for i in range(3):
if(self.grid[i][3] == self.grid[i + 1][3]):
p_a = True
return p_a
def stop_game(self):
''' Check every step if you lose to stop
the game when there is no possible movement
'''
full_cell = 0
for i in range(4):
for j in range(4):
if (self.grid[i][j] != 0):
full_cell += 1
if (full_cell == 16 and not self.possible_action()):
self.status = False
return self.status
def stack(self):
''' Stack the grid to the left.
see example:
grid [0, 2, 0, 2] Become [2, 2, 0, 0]
[0, 0, 0, 8] [8, 0, 0, 0]
[4, 0, 0, 2] [4, 2, 0, 0]
[0, 2, 8, 0] [2, 8, 0, 0]
'''
new_grid = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
for i in range(4):
position = 0
for j in range(4):
if (self.grid[i][j] != 0):
new_grid[i][position] = self.grid[i][j]
position += 1
self.grid = new_grid
return self.grid
def merge_left(self):
''' Merge grid to the left.
see example:
grid = [0, 2, 2, 0] Become [0, 4, 0, 0]
[2, 4, 4, 2] [2, 8, 0, 2]
[0, 2, 0, 4] [0, 2, 0, 4]
[8, 8, 8, 8] [16, 0, 16, 0]
'''
for i in range(4):
for j in range(3):
if(self.grid[i][j] == self.grid[i][j+1]):
self.grid[i][j] = self.grid[i][j] * 2
self.grid[i][j + 1] = 0
self.score += self.grid[i][j]
return self.grid, self.score
def transpose(self):
''' Transpose the grid, usefull to make movement.
All movement are base on left merge, left stack
see example:
grid = [2, 2, 2, 2] Become [2, 0, 0, 0]
[0, 2, 2, 2] [2, 2, 0, 0]
[0, 0, 2, 2] [2, 2, 2, 0]
[0, 0, 0, 2] [2, 2, 2, 2]
'''
new_grid = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
for i in range(4):
for j in range(4):
new_grid[j][i] = self.grid[i][j]
self.grid = new_grid
return self.grid
def inverse(self):
''' Inverse the grid, usefull to make movement.
All movement are base on left merge, left stack
see example:
grid = [2, 2, 2, 2] Become [2, 2, 2, 2]
[0, 2, 2, 2] [2, 2, 2, 0]
[0, 0, 2, 2] [2, 2, 0, 0]
[0, 0, 0, 2] [2, 0, 0, 0]
'''
new_grid = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
for i in range(4):
for j in range(4):
new_grid[i][j] = self.grid[i][3-j]
self.grid = new_grid
return self.grid
def left_movement(self):
''' Move grid to the left
see example:
grid = [2, 2, 0, 0] Become [4, 0, 0, 0]
[0, 0, 2, 2] [4, 0, 0, 0]
[0, 0, 0, 2] [2, 0, 0, 0]
[4, 4, 0, 2] [8, 2, 0, 0]
'''
self.stack()
self.merge_left()
self.stack()
return self.grid, self.score
def up_movement(self):
''' Move grid to the top
see example:
grid = [2, 2, 0, 0] Become [2, 2, 2, 4]
[0, 0, 2, 2] [4, 4, 0, 2]
[0, 0, 0, 2] [0, 0, 0, 0]
[4, 4, 0, 2] [0, 0, 0, 0]
'''
self.transpose()
self.stack()
self.merge_left()
self.stack()
self.transpose()
return self.grid, self.score
def down_movement(self):
''' Move grid to the bottom
see example:
grid = [2, 2, 0, 0] Become [0, 0, 0, 0]
[0, 0, 2, 2] [0, 0, 0, 0]
[0, 0, 0, 2] [2, 2, 0, 2]
[4, 4, 0, 2] [4, 4, 2, 4]
'''
self.transpose()
self.inverse()
self.stack()
self.merge_left()
self.stack()
self.inverse()
self.transpose()
return self.grid, self.score
def right_movement(self):
''' Move grid to the right
see example:
grid = [2, 2, 0, 0] Become [0, 0, 0, 4]
[0, 0, 2, 2] [0, 0, 0, 4]
[0, 0, 0, 2] [0, 0, 0, 2]
[4, 4, 0, 2] [0, 0, 8, 2]
'''
self.inverse()
self.left_movement()
self.inverse()
return self.grid, self.score
def main(self):
''' Main game launch this function to play
The command are classical zqsd (azerty keyboard)
Command : z => up
Command : q => left
Command : d => right
Command : s => down
to do an action you must select a direction and press enter
to quit write "quit" and press enter
'''
self.newcell_start()
self.newcell()
self.display()
while(self.status):
x = input('press command')
grid_test = self.grid
if (x.upper() == 'D'):
self.right_movement()
if (x.upper() == 'Z'):
self.up_movement()
if (x.upper() == 'S'):
self.down_movement()
if (x.upper() == 'Q'):
self.left_movement()
if (x.upper() == 'QUIT'):
self.status = False
self.sup_2048()
self.stop_game()
if self.status and self.grid != grid_test :
self.newcell()
self.display()
if self.status is False:
if self.goal >= 1:
print(f'Game over, you win ! {self.goal} created.\n Your score is {self.score}')
else:
print(f'Game over, you lose ! Your score is {self.score}')
if self.score > 730: # empirical mean see Algo_play
print(f'you did better than random IA')
else:
print(f'you did worse than random IA')
def demo(self):
""" Demo of an AI game (displayed)
"""
directions = ['z', 'q', 's', 'd']
self.newcell_start()
self.newcell()
self.display()
while(self.status):
time.sleep(2)
x = random.choice(directions)
grid_test = self.grid
if (x.upper() == 'D'):
self.right_movement()
if (x.upper() == 'Z'):
self.up_movement()
if (x.upper() == 'S'):
self.down_movement()
if (x.upper() == 'Q'):
self.left_movement()
if (x.upper() == 'QUIT'):
self.status = False
self.stop_game()
if self.status and self.grid != grid_test:
self.newcell()
self.display()
print(f'IA lost play {x} movement')
if self.status is False:
print(f'IA lost is score is {self.score}')
def random_2048(self):
""" AI game with random movements only.
"""
self.newcell_start()
self.newcell()
while(self.status):
x = random.choice(self.directions)
grid_test = self.grid
if (x.upper() == 'D'):
self.right_movement()
if (x.upper() == 'Z'):
self.up_movement()
if (x.upper() == 'S'):
self.down_movement()
if (x.upper() == 'Q'):
self.left_movement()
self.stop_game()
if self.status and self.grid != grid_test:
self.newcell()
def clockwise_2048(self):
""" AI game with clockwise movement (starting movement
is randomized)
"""
self.newcell_start()
self.newcell()
x = random.choice(self.directions)
#count = 0
while(self.status):
x = self.directions[self.directions.index(x) - 1]
grid_test = self.grid
if (x.upper() == 'D'):
self.right_movement()
if (x.upper() == 'Z'):
self.up_movement()
if (x.upper() == 'S'):
self.down_movement()
if (x.upper() == 'Q'):
self.left_movement()
self.stop_game()
if self.status and self.grid != grid_test:
self.newcell()
#count = (count + 1) % 4
def opposite_2048(self):
""" AI game with only a first random movement and its opposite one """
self.newcell_start()
self.newcell()
x = random.choice(self.directions)
block_game = 0
while(self.status):
x = self.directions[self.directions.index(x) - 2]
grid_test = self.grid
if (x.upper() == 'D'):
self.right_movement()
if (x.upper() == 'Z'):
self.up_movement()
if (x.upper() == 'S'):
self.down_movement()
if (x.upper() == 'Q'):
self.left_movement()
self.stop_game()
if self.grid == grid_test:
block_game += 1
if self.status and self.grid != grid_test:
self.newcell()
if block_game > 3:
self.status = False
def adjacent_2048(self):
""" AI game with only a first random movement and one of its adjacent ones """
self.newcell_start()
self.newcell()
x = random.choice(self.directions)
x0 = random.choice(self.directions)
x_adj = random.choice([self.directions[self.directions.index(x0) - 3], self.directions[self.directions.index(x0) - 1]])
x = x_adj
block_game = 0
while(self.status):
if x == x_adj:
x = x0
else: x = x_adj
grid_test = self.grid
if (x.upper() == 'D'):
self.right_movement()
if (x.upper() == 'Z'):
self.up_movement()
if (x.upper() == 'S'):
self.down_movement()
if (x.upper() == 'Q'):
self.left_movement()
self.stop_game()
if self.grid == grid_test:
block_game += 1
if self.status and self.grid != grid_test:
self.newcell()
if block_game > 3:
self.status = False
# Launch_game = Game()
# print('Command : z => up')
# print('Command : q => left')
# print('Command : d => right')
# print('Command : s => down')
# print('to do an action you must select a direction and press enter')
# Launch_game.main() # Launch game
class Game_6561():
""" This class represent gamegrid and function"""
def __init__(self):
""" Create new grid """
self.grid = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
self.score = 0
self.status = True
def newcell_start(self):
''' Add new cell to the grid when grid is empty.
Probability are 1/10 to be a 6
9/10 to be a 3
see example:
grid [0, 0, 0] Become [0, 0, 3]
[0, 0, 0] [0, 0, 0]
[0, 0, 0] [0, 0, 0]
'''
new_cell = 3
pos1 = random.randint(a=0, b=2)
pos2 = random.randint(a=0, b=2)
if random.uniform(a=0, b=1) > 0.90:
new_cell = 6
self.grid[pos1][pos2] = new_cell
return self.grid
def newcell(self):
''' Add new cell to the grid.
Probability are 1/10 to be a 6
9/10 to be a 3
see example:
grid [0, 3, 3] Become [3, 3, 0]
[0, 0, 0] [0, 0, 0]
[0, 0, 0] [0, 6, 0]
'''
empty_cell = []
new_cell = 3
pos = (0, 0)
for i in range(3):
for j in range(3):
if (self.grid[i][j] == 0):
empty_cell.append((i, j))
if random.uniform(a=0, b=1) > 0.90:
new_cell = 6
todo = len(empty_cell)
if todo == 0:
todo += 1
pos = random.randint(a=0, b=todo-1)
if len(empty_cell) == 0:
pos = [0, 0]
else:
pos = empty_cell[pos]
a, b = pos[0], pos[1]
self.grid[a][b] = new_cell
return self.grid
def display(self):
''' Display grid and score.
see example:
[0, 3, 0]
[0, 0, 0]
[0, 0, 3]
Your score is 6
'''
print(self.grid[0])
print(self.grid[1])
print(self.grid[2])
print(f'Your score is {self.score}')
def possible_action(self):
'''Checks if a movement is possible on the grid'''
p_a = False
for i in range(2):
for j in range(2):
if(self.grid[i][j] == self.grid[i + 1][j] or self.grid[i][j] == self.grid[i][j + 1]):
p_a = True
for j in range(2):
if(self.grid[2][j] == self.grid[2][j + 1]):
p_a = True
for i in range(2):
if(self.grid[i][2] == self.grid[i + 1][2]):
p_a = True
return p_a
def stop_game(self):
''' Check every step if you lose to stop
the game when there is no possible movement
'''
full_cell = 0
for i in range(3):
for j in range(3):
if (self.grid[i][j] != 0):
full_cell += 1
if (full_cell == 9 and not self.possible_action()):
self.status = False
return self.status
def stack(self):
''' Stack the grid to the left.
see example:
grid [0, 3, 0] Become [3, 0, 0]
[0, 0, 0] [0, 0, 0]
[9, 0, 0] [9, 0, 0]
'''
new_grid = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for i in range(3):
position = 0
for j in range(3):
if (self.grid[i][j] != 0):
new_grid[i][position] = self.grid[i][j]
position += 1
self.grid = new_grid
return self.grid
def merge_left(self):
''' Merge grid to the left.
see example:
grid = [0, 3, 3] Become [0, 9, 0]
[9, 9, 0] [27, 0, 0]
[0, 0, 3] [0, 0, 3]
'''
for i in range(3):
for j in range(2):
if(self.grid[i][j] == self.grid[i][j+1]):
self.grid[i][j] = self.grid[i][j] * 3
self.grid[i][j + 1] = 0
self.score += self.grid[i][j]
return self.grid, self.score
def transpose(self):
''' Transpose the grid, usefull to make movement.
All movement are base on left merge, left stack
see example:
grid = [3, 3, 3] Become [3, 0, 0]
[0, 3, 3] [3, 3, 0]
[0, 0, 3] [3, 3, 3]
'''
new_grid = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for i in range(3):
for j in range(3):
new_grid[j][i] = self.grid[i][j]
self.grid = new_grid
return self.grid
def inverse(self):
''' Inverse the grid, usefull to make movement.
All movement are base on left merge, left stack
see example:
grid = [3, 3, 3] Become [3, 3, 3]
[0, 3, 3] [3, 3, 3]
[0, 0, 3] [3, 3, 0]
'''
new_grid = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for i in range(3):
for j in range(3):
new_grid[i][j] = self.grid[i][2-j]
self.grid = new_grid
return self.grid
def left_movement(self):
''' Move grid to the left
see example:
grid = [6, 0, 6] Become [9, 0, 0]
[0, 0, 6] [6, 0, 0]
[0, 0, 3] [3, 0, 0]
'''
self.stack()
self.merge_left()
self.stack()
return self.grid, self.score
def up_movement(self):
''' Move grid to the top
see example:
grid = [3, 3, 0] Become [3, 3, 3]
[0, 0, 3] [9, 9, 0]
[0, 9, 0] [0, 0, 0]
'''
self.transpose()
self.stack()
self.merge_left()
self.stack()
self.transpose()
return self.grid, self.score
def down_movement(self):
''' Move grid to the bottom
see example:
grid = [9, 9, 0] Become [0, 0, 0]
[0, 0, 3] [0, 0, 0]
[0, 0, 0] [9, 9, 3]
'''
self.transpose()
self.inverse()
self.stack()
self.merge_left()
self.stack()
self.inverse()
self.transpose()
return self.grid, self.score
def right_movement(self):
''' Move grid to the right
see example:
grid = [3, 3, 0] Become [0, 0, 9]
[0, 0, 3] [0, 0, 3]
[9, 0, 3] [0, 9, 3]
'''
self.inverse()
self.left_movement()
self.inverse()
return self.grid, self.score
def main(self):
''' Main game launch this function to play
The command are classical zqsd (azerty keyboard)
Command : z => up
Command : q => left
Command : d => right
Command : s => down
to do an action you must select a direction and press enter
to quit write "quit" and press enter
'''
self.newcell_start()
self.newcell()
self.display()
while(self.status):
x = input('press command')
grid_test = self.grid
if (x.upper() == 'D'):
self.right_movement()
if (x.upper() == 'Z'):
self.up_movement()
if (x.upper() == 'S'):
self.down_movement()
if (x.upper() == 'Q'):
self.left_movement()
if (x.upper() == 'QUIT'):
self.status = False
self.stop_game()
if self.status and self.grid != grid_test:
self.newcell()
self.display()
if self.status is False:
print(f'you lose your score is {self.score}')
def demo(self):
self.newcell_start()
self.newcell()
self.display()
directions = ['z', 'q', 's', 'd']
while(self.status):
time.sleep(2)
x = random.choice(directions)
x = input('press command')
grid_test = self.grid
if (x.upper() == 'D'):
self.right_movement()
if (x.upper() == 'Z'):
self.up_movement()
if (x.upper() == 'S'):
self.down_movement()
if (x.upper() == 'Q'):
self.left_movement()
if (x.upper() == 'QUIT'):
self.status = False
self.stop_game()
if self.status and self.grid != grid_test:
self.newcell()
self.display()
if self.status is False:
print(f'you lose your score is {self.score}')
#AAA = Game_2048().clockwise_2048()
#AAA.random_2048()
#print(AAA.score)
def Lauchgame():
AAA = Game_2048()
AAA.main() |
# Задание 2.3.
# По аналогии с тем, как я поступил с факториалом, сделайте вывод каждого
# шага вычисления функции fibo на экран, чтобы понять что реально тут
# происходит и почему функция работает медленно.
# def fibo(n):
# if n == 0: return 0
# if n == 1: return 1
# return fibo(n - 1) + fibo(n - 2)
# http://heller.ru/course/viewtopic.php?f=7&t=24
print("Week 2 @ 2.3")
def fibo_with_recursion(n):
if n == 0: return 0
if n == 1: return 1
else:
a = fibo_with_recursion(n - 1)
b = fibo_with_recursion(n - 2)
result = a + b
print("fibo(n - 1) = " + str(a) + " fibo(n - 2) = " + str(b) +
" result = " + str(result))
return result
print("Введите число: ")
guess = int(input())
print("fibo (" +str(guess) + ") = " + str(fibo_with_recursion(guess)))
input()
|
def mult(*args):
result = 1
for arg in args:
result *= arg
return result
print(mult(1,2,3,4))
def sumpowers(*args, power=1):
result = 1
for arg in args:
result *= arg ** power
return result
print(sumpowers(1,2,3,4))
print(sumpowers(1,2,3,4,power=2))
|
def main():
print()
i = 0
for i in range (0, 256):
n = chr (i)
print(str(i) + ":", end='')
print(n)
print()
main()
|
var = input("var: ")
try:
var != int(var)
except ValueError:
print ("var is a str")
|
# LARISSA TENORIO E THALES VALDSON
from random import shuffle
def geraLista(tam):
lista = list(range(1, tam + 1))
shuffle(lista)
return lista
def not_bubble_sort(lista):
elementos = len(lista)/2
ordenado = False
ordenado2= False
while not ordenado:
ordenado = True
for i in range(int(elementos)):
if lista[i] > lista[i + 1]:
lista[i], lista[i + 1] = lista[i + 1], lista[i]
ordenado = False
while not ordenado2:
ordenado2 = True
for i in range(len(lista)-1,int(elementos),-1):
if lista[i] < lista[i - 1]:
lista[i], lista[i - 1] = lista[i - 1], lista[i]
ordenado2 = False
lista1=lista[:int(elementos)]
lista2=lista[int(elementos) :]
final = []
while lista1 or lista2:
if len(lista1) and len(lista2):
if lista1[0] < lista2[0]:
final.append(lista1.pop(0))
else:
final.append(lista2.pop(0))
if not len(lista1):
if len(lista2): final.append(lista2.pop(0))
if not len(lista2):
if len(lista1): final.append(lista1.pop(0))
return final
size = [10, 20, 30]
time = []
for s in size:
lista = geraLista(s)
print('Nao ordenada: ', lista)
ordenada = not_bubble_sort(lista)
print('Ordenada: ', ordenada)
print('\n')
|
def maxSubArray(nums):
max_so_far = curr_so_far = -float('inf')
for i in range(len(nums)):
curr_so_far += nums[i] # Add curr number
print('1',curr_so_far)
curr_so_far = max(curr_so_far, nums[i]) # Check if should abandon accumulated value so far if it's a burden due to negative value accumulated
#print('2',curr_so_far)
max_so_far = max(max_so_far, curr_so_far) # Update answer
print('3',max_so_far)
return max_so_far
print(maxSubArray([-2,1, 3, 4, -3, 3]))
#model solution
def maxSubArray(nums):
for i in range(1, len(nums)):
if nums[i-1] > 0:
nums[i] += nums[i-1]
print(nums)
return max(nums)
print(maxSubArray([-2,1,-3,4,-1,2,1,-5,4]))
#model solution
def maxSubArray(A):
if not A:
return 0
curSum = maxSum = A[0]
for num in A[1:]:
curSum = max(num, curSum + num)
maxSum = max(maxSum, curSum)
return maxSum
|
# *-* encoding: utf-8 *-*
import re
from abc import ABC, abstractmethod
from typing import Dict
class Factor(ABC):
@abstractmethod
def __init__(self):
pass
@abstractmethod
def compute(self, segment: str):
"""
Computes the factor on the tokens in the segment.
"""
raise NotImplementedError()
def compute_json(self,
jobj: Dict):
"""
Extracts the required field from the JSON object and calls compute() with it.
"""
raise NotImplementedError()
class SubwordFactor(Factor):
def __init__(self):
pass
def compute_sp(self, sp_str: str) -> str:
"""
iron cement is a ready for use paste which is laid as a fillet by putty knife or finger in the mould edges ( corners ) of the steel ingot mould .
▁iron ▁c ement ▁is ▁a ▁ready ▁for ▁use ▁past e ▁which ▁is ▁laid ▁as ▁a ▁fill et ▁by ▁put ty ▁kni fe ▁or ▁finger ▁in ▁the ▁mould ▁edge s ▁( ▁corner s ▁) ▁of ▁the ▁steel ▁in go t ▁mould ▁.
The options are:
O: a complete word
B: beginning of a multi-token word
I: interior of a multi-token word
E: end of a multi-token word
"""
def process_stack(stack):
factors_ = []
if len(stack) == 1:
factors.append('O')
elif len(stack) > 1:
stack[0] = 'B'
# all interior words are 'I'
for i in range(1, len(stack) - 1):
stack[i] = 'I'
stack[-1] = 'E'
factors_ += stack
return factors_
factors = []
tokens = sp_str.split()
stack = [tokens.pop(0)]
for i, token in enumerate(tokens):
if token.startswith('▁'):
factors += process_stack(stack)
stack = []
stack.append(token)
factors += process_stack(stack)
return ' '.join(factors)
def compute_bpe(self, bpe_str: str) -> str:
"""
Computes NER-style features for a BPE stream. e.g.,
The boy ate the waff@@ le .
O O O O B E O
The options are:
O: a complete word
B: beginning of a multi-token word
I: interior of a multi-token word
E: end of a multi-token word
:param bpe_str: The BPE string.
:return: A string of BPE factors.
"""
factors = []
was_in_bpe = False
for i, token in enumerate(bpe_str.split()):
now_in_bpe = token.endswith('@@')
if was_in_bpe:
if now_in_bpe:
factor = 'I'
else:
factor = 'E'
else:
if now_in_bpe:
factor = 'B'
else:
factor = 'O'
was_in_bpe = now_in_bpe
factors.append(factor)
return ' '.join(factors)
def compute(self, subword_str) -> str:
"""
Computes features over a subword string.
Automatically determines whether its SentencePiece or BPE.
"""
return self.compute_sp(subword_str) if '▁' in subword_str else self.compute_bpe(subword_str)
def compute_json(self, jobj):
return self.compute(jobj['subword_text'])
class CaseFactor(Factor):
def __init__(self):
pass
def case(self, token):
if token.isupper():
return 'UPPER'
elif token.istitle():
return 'Title'
elif token.islower():
return 'lower'
else:
return '-'
def compute(self, segment: str) -> str:
return ' '.join([self.case(token) for token in segment.split()])
def compute_json(self, jobj: Dict) -> str:
return self.compute(jobj['tok_text'])
class MaskFactor(Factor):
def __init__(self):
self.mask_regex = re.compile('__[A-Za-z0-9]+(_\d+)?__')
def is_mask(self, token: str):
return 'Y' if self.mask_regex.match(token) else 'n'
def compute(self, segment: str) -> str:
return ' '.join([self.is_mask(token) for token in segment.split()])
def compute_json(self, jobj: Dict) -> str:
return self.compute(jobj['text'])
|
def checkio(*args):
if len(args) == 0:
return 0
big, small = args[0],args[0]
for num in args:
if num > big:
big = num
if num < small:
small = num
return big - small
print(checkio(1,2,3))
# ! optimized
def checkio(*args):
if args:
return max(args) - min(args)
return 0 |
def sort_by_ext(files):
# your code here
return files
a = ['1.cad', '1.bat', '.aba','2.aa']
# => [['1', 'cad'], ['1', 'bat'], ['1', 'aa']]
a = [x.split('.') for x in a]
print(sorted(a,key=lambda k: (k[0],k[1])))
# ! checkio version
def sort_by_ext(files):
#
no_name = []
res = sorted([x.split('.') for x in files],key=lambda k: (k[1],k[0]))
print(res)
for i,ele in enumerate(res):
if ele[0] == '':
print('remove')
no_name.append(ele)
res.pop(i)
res = no_name + res
res = sorted(res,key=lambda k: len(k))
return [('.').join(x) for x in res] |
def yaml(a):
# your code here
dic = {}
# split based on \n
# find pos of ':' [0:index] => key [index+1:]=>value
# if value isdigit => int(value)
a = a.split('\n')
for word in a:
# remove line without content
if len(word):
word = word.replace('"', '').replace('\\','')
index = word.find(':')
key = word[:index]
value= word[index+2:]
value = int(value) if value.isdigit() else value
dic[key] = value
# print(dic)
return dic
# ! test yamel
# print(yaml("""name: Alex Fox
# age: 12
# class: 12b"""))
print(yaml("name: \"Alex \\\"Fox\\\"\"\nage: 12\n\nclass: 12b"))
|
import sys
import urllib.request
import os
def main():
if (len(sys.argv) >= 3):
filename = sys.argv[1]
directory = sys.argv[2]
if not os.path.exists(directory):
os.makedirs(directory)
f = open(filename, "r")
i = 0
urls = f.readlines()
for url in urls:
filenameToCreate = directory + "/" + "{:08d}".format(i) + ".jpg"
print(url)
print(filenameToCreate)
try:
urllib.request.urlretrieve(url, filenameToCreate)
i += 1
except:
print(url + " can't be downloaded")
else:
print("Arguments are missing")
#to run the program
#python3 scriptname.py filenameForData DirectoryNameToSavePictures
main()
|
WELCOME = "Welcome to the family, {}"
PERSON_EXISTS = "Sorry {} already exists!"
SPOUSE_EXISTS = "Sorry {} is already married!"
RELATIONSHIPS = set(["father", "mother", "grandfather", "grandmother",
"daughters", "sons", "brothers", "sisters",
"uncles", "aunts", "cousins", "grandsons",
"grandaughters", "wife", "husband"])
class Tree:
"""
An object that represents a family tree and the actions
that can be performed upon it.
"""
data = {}
def __init__(self, data):
self.data = data
def get_relationships(self, person, relation):
"""Query the different relationships in the family tree.
Args:
person (str): The person you are querying.
relation (str): The type relationship.
Returns:
str: The persons relations of type that was input
i.e. Brothers=John,Joe
"""
self.isvalid(person, relation)
relations = self.data[person][relation]
if type(relations) == list:
relations = ",".join(sorted(relations)).replace(" ", "")
return str.format("{0}={1}", relation.title(), relations.title())
def add_spouse(self, husband, wife):
"""Create a new wife or spouse for an existing person.
Args:
husband (str): The husband you'd like to create or get married.
wife (str): The wife you'd like to create or get married.
Raises:
ValueError: If both spouses already exist.
ValueError: If Neither spouse exists.
Returns:
str: A welcome message including the name of the new spouse.
"""
if set(("husband", "wife")) <= set(self.data.keys()):
raise ValueError(str.format(
"Both {0} and {1} already exist in your family tree.",
husband.title(), wife.title()))
if husband not in self.data.keys():
if wife not in self.data.keys():
raise ValueError(str.format(
"Neither {0} and {1} exist in your family tree.",
husband.title(), wife.title()))
if husband in self.data:
self.ispresent(wife)
self.ismarried(husband)
self.data[husband]["wife"] = wife
self.data[wife] = {"husband": husband}
return str.format(WELCOME, wife.title())
if wife in self.data:
self.ispresent(husband)
self.ismarried(wife)
self.data[wife]["husband"] = husband
self.data[husband] = {"wife": wife}
return str.format(WELCOME, husband.title())
def add_child(self, child, parent , relation):
"""Add a new child to a mother and implicitly it's father as well.
Args:
child (str): The child you'd like to create.
parent (str): The parent of the child.
relation (str): The relationship - son or daughter
Raises:
ValueError: If `child` already exists.
Returns:
str: A welcome message including the child's name.
"""
self.isvalid(parent, relation)
if relation in self.data[parent]:
if child in self.data[parent][relation]:
raise ValueError(str.format(PERSON_EXISTS, child.title()))
spouse_name = ""
spouse_relation = ""
parents = [parent]
spouse_relation = [x for x in self.data[parent].keys()
if x in ["husband", "wife"]]
if spouse_relation:
spouse_name = self.data[parent][spouse_relation[0]]
parents.append(spouse_name)
for p in parents:
if relation in self.data[p]:
self.data[p][relation].append(child)
else:
self.data[p][relation] = [child]
return str.format(WELCOME, child.title())
def isvalid(self, person, relation):
"""Check if a person is missing or the relationship input is valid.
Args:
person (str): The person input into the program.
relation (str): The relationship type input into the program.
Raises:
ValueError: If `person` is missing from the data.
ValueError: If `relation` is invalid.
"""
self.ismissing(person)
if relation not in RELATIONSHIPS:
raise KeyError(str.format("Sorry, {} not a supported relationship type",
relation.title()))
def ismissing(self, person):
"""Check if a person is missing from the data.
Args:
person (str): The person input into the program.
Raises:
ValueError: If `person` is missing from the data.
"""
if person not in self.data:
raise ValueError(str.format("{} is a not a member of this family.",
person.title()))
def ispresent(self, person):
"""Check if a person is alread represented in the data.
Args:
person (str): The person input into the program.
Raises:
ValueError: If `person` is represented in the data.
"""
if person in self.data:
raise ValueError(str.format(PERSON_EXISTS, person.title()))
def ismarried(self, person):
"""Check if a person is already married.
Args:
person (str): The person input into the program.
Raises:
ValueError: If `person` is already married.
"""
for k in self.data[person].keys():
if k in ["wife", "husband"]:
raise ValueError(str.format(SPOUSE_EXISTS, person.title()))
|
# encoding: utf-8;
from __future__ import generators
import re
from tokenexceptions import *
#
# Token Class. Now we're getting somewhere.
#
class Token( object ):
"""
A Token is the smallest unit of a program that can be considered in
abstraction. It has a type, which should probably be an Enum of some
sort, however those work in Python, and a value.
"""
def __init__( self, token_type, token_value ):
self.type = token_type
self.value = token_value
def __str__( self ):
return "Token: '%s' of type %s" % ( self.value, self.type )
def __eq__( self, other ):
if isinstance( other, Token ):
return self.type == other.type and self.value == other.value
else:
return NotImplemented
def __ne__( self, other ):
result = self.__eq__( other )
if result is NotImplemented:
return NotImplemented
else:
return not result
class TokenList( object ):
def __init__( self, tokens = None ):
self.__tokens = tokens
if self.__tokens is None:
self.__tokens = []
elif isinstance( self.__tokens, Token ):
self.__tokens = [ self.__tokens ]
self.__reset()
def append( self, to_append ):
"""Appends a token to the TokenList, and resets the internal pointer"""
if isinstance( to_append, Token ):
self.__tokens.append( to_append )
self.__reset()
elif isinstance( to_append, (list, tuple) ):
for value in to_append:
self.__tokens.append( value )
self.__reset()
else:
raise TypeError
def next( self ):
"""Returns the next token in the list, and advances the pointer"""
self.current += 1
return self.__get_token( self.current )
def peek( self ):
"""Returns the next token in the list, without advancing the pointer"""
newIndex = self.current + 1
return self.__get_token( newIndex )
#
# Private Helpers
#
def __reset( self ):
"""Resets the internal pointer to the beginning of the list, and reevaluates the size"""
self.current = -1
self.length = len( self.__tokens )
def __get_token( self, x ):
"""Returns a specific token"""
if x < self.length:
return self.__tokens[ x ]
else:
return None
#
# Iterable
#
def __iter__(self):
return (t for t in self.__tokens)
#
# Equality
#
def __eq__( self, other ):
if isinstance( other, TokenList ):
if other.length == self.length:
a = other.next()
b = self.next()
while a is not None or b is not None:
if a != b:
return False
a = other.next()
b = self.next()
return True
else:
return False
else:
return NotImplemented
def __ne__( self, other ):
result = self.__eq__( other )
if result is NotImplemented:
return NotImplemented
else:
return not result
#
# Conversion
#
def __str__( self ):
str_buffer = ''
cur = 0
for token in self.__tokens:
str_buffer += "%d) %s\n" % ( cur, token )
cur += 1
return str_buffer
class Tokenizer( object ):
### Generic "Constants" to be overridden in subclasses
WHITESPACE = re.compile("\s")
SPACE = re.compile("[ \t]")
TERMINATOR = re.compile("[\n\r]")
BEGIN_STRING = re.compile("['\"]")
CHARACTER = re.compile("[a-zA-Z]")
NUMBER = re.compile("[0-9]")
NUMBER_SIGN = re.compile("[-+]")
IDENTIFIER = re.compile("[a-zA-Z0-9_]")
NUMBER_SEPERATOR = re.compile("[\.]")
NUMBER_EXPONENT = re.compile("[Ee]")
BEGIN_COMMENT = re.compile("[/]")
def __init__( self, string_to_tokenize = ''):
self.original = string_to_tokenize
self.length = len( string_to_tokenize )
self.index = -1
self.tokens = TokenList()
#
# Helper Methods (Private)
#
def __peek( self ):
"""Return the next character (or None), but don't advance the index."""
newIndex = self.index + 1
return self.__get_char( newIndex )
def __keep( self ):
"""Return the previous character (or None), but don't retract the index."""
newIndex = self.index - 1
return self.__get_char( newIndex )
def __char_is( self, c, char_type ):
"""Returns true if the given character is not none, and matches the given type"""
if c is not None:
return char_type.match( c )
else:
return False
def __get_char( self, x ):
if x < self.length:
return self.original[ x ]
else:
return None
#
# Helper Methods (Not so private (used by subclasses))
#
def cur_char( self ):
"""Return the current character (or None)."""
return self.__get_char( self.index )
def next_char( self ):
"""Return the next character (or None), and advance the index."""
self.index += 1
return self.__get_char( self.index )
def next_x_chars( self, x = 1 ):
"""Return the next X characters (or None if there aren't enough), and advance the index."""
first = self.index + 1
last = first + x
if last < self.length:
return self.original[ first : last ]
else:
return None
def cur_char_is( self, char_type ):
"""Returns true if the next character is of a certain type (e.g. matches a given regex)"""
c = self.cur_char()
return self.__char_is( c, char_type )
def next_char_is( self, char_type ):
"""Returns true if the next character is of a certain type (e.g. matches a given regex)"""
c = self.__peek()
return self.__char_is( c, char_type )
def prev_char_is( self, char_type ):
"""Returns true if the previous character was of a certain type."""
c = self.__keep()
return self.__char_is( c, char_type )
def token_generator( self ):
pass
#
# Public Methods
#
def tokenize( self ):
for token in self.token_generator():
self.tokens.append( token )
return self.tokens
#
# Generic Tokens (can/should be overridden by subclasses)
#
def process_literal_string( self ):
"""Process a 'generic' string, either raising an error or retuning a string Token"""
c = self.cur_char()
start_index = self.index
quote_char = c
str_buffer = ''
### Will exit this loop only via raising an error,
### or through a `break` when we find a closing quote.
while True:
c = self.next_char()
### Raise an error?
if ( c is None or self.TERMINATOR.match( c ) ):
raise UnterminatedString( str_buffer, start_index, self.index )
# Need a test here for control characters
# elif [control characters].match( c ) ):
# raise StringContainsControlCharacters( str_buffer, start_index, self.index )
### Closing Quote?
if ( c == quote_char ):
return Token( '(STRING)', str_buffer )
break
### Ok, then.
### Escaped?
if ( c == '\\'):
escapee = self.next_char()
if ( escapee is None):
raise UnterminatedString( str_buffer, start_index, self.index )
### I wish Python had a `switch` statement.
if ( 'b' == escapee ):
c = '\b'
elif ( 'f' == escapee ):
c = '\f'
elif ( 'n' == escapee ):
c = '\n'
elif ( 'r' == escapee ):
c = '\r'
elif ( 't' == escapee ):
c = '\t'
elif ( 'u' == escapee ):
base16 = self.next_x_chars( 4 )
if ( base16 is None ):
raise UnterminatedString( str_buffer, start_index, self.index )
else:
try:
c = chr( int( base16, 16 ) )
except ( ValueError, TypeError ):
raise UnterminatedString( str_buffer, start_index, self.index )
else:
c += escapee
### Append, and move on
str_buffer += c
def process_literal_number( self ):
"""Process a 'generic' number, either raising an error, or returning a number Token"""
c = self.cur_char()
start_index = self.index
str_buffer = c
while ( self.next_char_is( self.NUMBER ) ):
str_buffer += self.next_char()
if ( self.next_char_is( self.NUMBER_SEPERATOR ) ):
str_buffer += self.next_char()
while ( self.next_char_is( self.NUMBER ) ):
str_buffer += self.next_char()
if ( self.next_char_is( self.NUMBER_EXPONENT ) ):
str_buffer += self.next_char()
if ( self.next_char_is( self.NUMBER_SIGN ) ):
str_buffer += self.next_char()
if ( not self.next_char_is( self.NUMBER ) ):
raise NumberBadExponent( str_buffer, start_index, self.index )
while ( self.next_char_is( self.NUMBER ) ):
str_buffer += self.next_char()
if ( self.next_char_is( self.CHARACTER ) ):
raise NumberFollowedByCharacter( str_buffer, start_index, self.index )
else:
return Token( '(NUMBER)', str_buffer )
def process_identifier( self ):
"""Process a 'generic' identifier, either raising an error, or returning an identifier Token"""
c = self.cur_char()
str_buffer = c
while ( self.next_char_is( self.IDENTIFIER ) ):
str_buffer += self.next_char()
return Token( '(IDENTIFIER)', str_buffer ) |
Nama = input(str("Masukkan Nama Anda: "))
Umur = int(input("Masukkan Umur Anda: "))
Tinggi = float(input("Masukkan Tinggi Anda (cm): "))
txt = "Nama saya {}, umur saya {} tahun dan tinggi saya {} cm".format(Nama, Umur, Tinggi)
print(txt)
|
my_list = [1, 1, 1, 1]
print(my_list)
my_list[0] = 3
print(my_list)
my_dict = {
"nama" : "Andy",
"umur" : "30"
}
print(my_dict) |
#!/usr/bin/env python
from __future__ import print_function
from builtins import input
from builtins import str
import sys
import pmagpy.pmag as pmag
def main():
"""
NAME
stats.py
DEFINITION
calculates Gauss statistics for input data
SYNTAX
stats [command line options][< filename]
INPUT
single column of numbers
OPTIONS
-h prints help message and quits
-i interactive entry of file name
-f input file name
-F output file name
OUTPUT
N, mean, sum, sigma, (%)
where sigma is the standard deviation
where % is sigma as percentage of the mean
stderr is the standard error and
95% conf.= 1.96*sigma/sqrt(N)
"""
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
if '-i' in sys.argv:
file=input("Enter file name: ")
f=open(file,'r')
elif '-f' in sys.argv:
ind=sys.argv.index('-f')
file=sys.argv[ind+1]
f=open(file,'r')
else:
f=sys.stdin
ofile = ""
if '-F' in sys.argv:
ind = sys.argv.index('-F')
ofile= sys.argv[ind+1]
out = open(ofile, 'w + a')
data=f.readlines()
dat=[]
sum=0
for line in data:
rec=line.split()
dat.append(float(rec[0]))
sum+=float(float(rec[0]))
mean,std=pmag.gausspars(dat)
outdata = len(dat),mean,sum,std,100*std/mean
if ofile == "":
print(len(dat),mean,sum,std,100*std/mean)
else:
for i in outdata:
i = str(i)
out.write(i + " ")
if __name__ == "__main__":
main()
|
#!/usr/bin/env python
from __future__ import print_function
from builtins import input
from builtins import str
from builtins import range
import sys
import pmagpy.pmag as pmag
def main():
"""
Welcome to the thellier-thellier experiment automatic chart maker.
Please select desired step interval and upper bound for which it is valid.
e.g.,
50
500
10
600
a blank entry signals the end of data entry.
which would generate steps with 50 degree intervals up to 500, followed by 10 degree intervals up to 600.
chart is stored in: chart.txt
"""
print(main.__doc__)
if '-h' in sys.argv:sys.exit()
cont,Int,Top=1,[],[]
while cont==1:
try:
interval=input(" Enter desired treatment step interval: <return> to quit ")
if interval!="":
Int.append(int(interval))
else:cont=0
if cont:
top= input(" Enter upper bound for this interval: ")
if top!="":
Top.append(int(top))
except:
cont=0
pmag.chart_maker(Int,Top)
if __name__ == "__main__":
main()
|
def bubble_sort(arr:list, reverse=False):
n = len(arr)
if n <= 1:
return
if reverse:
for i in range(n-1, -1, -1):
for j in range(0, i):
if arr[j] < arr[j+1]:
tmp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = tmp
# so, arr[i] is the maximal ele in arr[0, i]
else:
for i in range(0, n, 1):
for j in range(n-2, i-1, -1):
if arr[j] > arr[j+1]:
tmp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = tmp
# so, arr[i] holds the minimal ele in [i, n)
|
# 2019-9-24
class Solution:
def domino(self, n: int, m: int, broken: list) -> int:
# count <= n*m-1
# 返回下一个空白格的坐标
def get_next_ord(count: int):
if count <= LIMIT:
x, y = count // m, count % m
#print(x, y)
while not chess[x][y]:
# 从左往右v
y += 1
if y >= m:
x += 1
y = 0
if x >= n:
x, y = -1, -1
break
return (x, y)
else:
return (-1, -1)
# prev_num是上一层发现的最大的覆盖数
def search(count: int, prev_num:int) -> int:
if count > LIMIT:
return prev_num
x, y = get_next_ord(count)
result = prev_num
nonlocal stime
stime += 1
if chess[x][y]:
#print("Searching: ", x, y, prev_num, count)
chess[x][y] = False
if y+1< m and chess[x][y+1]:
chess[x][y+1] = False
result = max(result, search(count+1, prev_num+1)) # 放下一个覆盖
chess[x][y+1] = True
if x+1< n and chess[x+1][y]:
chess[x+1][y] = False
result = max(result, search(count+1, prev_num+1))
chess[x+1][y] = True
chess[x][y] = True
# print("search result: ", result)
return result
res = 0
if n <= 1 or m <= 1:
return res
# n行m列矩阵上有 一些坏掉的格子(Broken)
# 搜索 + 回溯 + 剪枝
# 有横着放\ 竖着放两种
#print(n, m, broken)
chess = [[True for _ in range(m)] for _ in range(n)] # T 表示没被覆盖
if broken:
for x, y in broken:
chess[x][y] = False
# 对于(x, y) 检查右\下是否有空
# 用一个计数器, 得到..坐标
cnt = 0
LIMIT = n*m - 1
stime = 0
#while cnt <= LIMIT:
#res = max(res, search(count=cnt, prev_num=0)) # if chess[0][0] == False, stop. -> res = 0
#cnt += 1
res = search(count=0, prev_num=0)
#print("res = ", res)
print("Search time: ", stime)
else:
res =
return res
def SearchChess(self, n:int, m:int, broken: list) -> int:
def next_x(x:int, y:int) -> int:
next = x+1
while next < n and not chess[next][y]:
next += 1
return next
def next_y(x:int, y: int) -> int:
next = y+1
while next < m and not chess[x][next]:
next += 1
return next
def next_dig(x:int, y:int) -> (int, int):
return (x+1, y+1)
def search(prev_x:int, prev_y:int, prev_res:int) -> int:
result = prev_res
x, y = 0, 0
if chess[prev_x][prev_y]:
x = next_x(prev_x, prev_y)
if x < n and chess[x][prev_y]:
chess[x][prev_y] = False
result = max(result, search(x, prev_y, prev_res+1))
chess[x][prev_y] = True
y = next_y(prev_x, prev_y)
if y < m and chess[prev_x][y]:
chess[prev_x][y] = False
result = max(result, search(prev_x, y, prev_res+1))
chess[prev_x][y] = True
return result
res = 0
chess = [[True for _ in range(m)] for _ in range(n)] # T 表示没被覆盖
for x, y in broken:
chess[x][y] = False
return res
s = Solution()
assert 4 == s.domino(n = 3, m = 3, broken = [])
assert 2 == s.domino(n = 2, m = 3, broken = [[1, 0], [1, 1]])
assert 6 == s.domino(n = 4, m = 3, broken=[])
assert 1 == s.domino(n=2, m=2, broken=[[0, 0]])
assert 20 == s.domino(n=5, m=8, broken=[])
assert 16 == s.domino(n=6, m=6, broken=[[0, 0], [0,1], [1, 0], [1, 1]])
assert 0 == s.domino(n=2, m=2, broken=[[1, 1], [0, 0]])
assert 6 == s.domino(n=4, m=4, broken=[[0, 0], [0, 3], [3, 0], [3, 3]])
print(s.domino(n=8, m=6, broken=[]))
|
# 2020-01-20
from typing import List
class RedBlackTree:
"""
CLRS:
1. Each node is either red or black.
2. The root of a rbt is black.
3. Leaves are black.
4. A red node must have 2 black children.
5. For each node A, all simple paths from A to a descendant leaves, contain the same number of black nodes.
"""
class RBTNode:
COLOR_RED = 0
COLOR_BLACK = 1
def __init__(self, key, val, color,
left=None,
right=None,
father=None):
self.key = key
self.val = val
self.color = color
self.right = right
self.left = left
self.father = father
def __repr__(self):
return "(key={}, val={}, left={}, right={}, father={})".format(
self.key, self.val, id(self.left), id(self.right), id(self.father)
)
def __eq__(self, other):
if self and other:
return id(self) == id(other) # 防止无限递归
elif not self and not other:
return True
else:
return False
def set_black(self):
self.color = RedBlackTree.RBTNode.COLOR_BLACK
def set_red(self):
self.color = RedBlackTree.RBTNode.COLOR_RED
def get_kv(self):
return self.key, self.val
def __init__(self):
self.__init_leaf()
self.__root = self.__nil
def __eq__(self, other):
pass
def __init_leaf(self):
self.__nil = RedBlackTree.RBTNode(None, None, color=RedBlackTree.RBTNode.COLOR_BLACK)
self.__nil.left = self.__nil
self.__nil.right = self.__nil
self.__nil.father = self.__nil
'''
#===============================================================
y x
/ \ <-------- left rotate ------- / \
x c a y
/ \ --------- right rotate ------> / \
a b a b
#===============================================================
恢复原状:
left_rotate(x).right_rotate(x.father) 或者
right_rotate(y).left_rotate(y.father)
'''
def __left_rotate(self, x:RBTNode):
y = x.right
x.right = y.left
if y.left != self.__nil:
y.left.father = x
y.father = x.father
if x.father == self.__nil:
self.__root = y
elif x == x.father.left:
x.father.left = y
else:
x.father.right = y
y.left = x
x.father = y
return self
def __right_rotate(self, y: RBTNode):
# right rotate is symmetric.
x = y.left
y.left = x.right
if x.right != self.__nil:
x.right.father = y
x.father = y.father
if y.father == self.__nil:
self.__root = x
elif y == y.father.left:
y.father.left = x
else:
y.father.right = x
x.right = y
y.father = x
return self
def __insert_node(self, node: RBTNode):
leaf = self.__nil
y = self.__nil
x = self.__root
while x != leaf:
y = x
if node.key <= x.key:
x = x.left
else:
x = x.right
node.father = y
if y == leaf:
self.__root = node
elif node.key <= y.key:
y.left = node
else:
y.right = node
# 以上都是常见的BST插入
self.__insert_fixup(node)
return self
def __delete_node(self, node:RBTNode):
"""
CLRS: page 324
:param node:
:return:
"""
assert node
z, y = node, node
x = None
y_origin_color = y.color
if z.left == self.__nil:
x = z.right
self.__transplant(z, z.right)
elif z.right == self.__nil:
x = z.left
self.__transplant(z, z.left)
else:
y = self.__find_min(z.right)
y_origin_color = y.color
x = y.right
if y.father == z:
x.father = y
else:
self.__transplant(y, y.right)
y.right = z.right
y.right.father = y
self.__transplant(z, y)
y.left = z.left
y.left.father = y
y.color = z.color
if y_origin_color == RedBlackTree.RBTNode.COLOR_BLACK:
self.__delete_fixup(x)
def __find_min(self, node:RBTNode) -> RBTNode:
leaf = self.__nil
assert node != leaf
while node != leaf and node.left != leaf:
node = node.left
return node
def __find_max(self, node:RBTNode) -> RBTNode:
leaf = self.__nil
assert node != leaf
while node != leaf and node.right != leaf:
node = node.right
return node
def __transplant(self, u:RBTNode, v:RBTNode):
if u.father == self.__nil:
self.__root = v
elif u == u.father.left:
u.father.left = v
else:
u.father.right = v
v.father = u.father
def __search_node(self, key):
p = self.__root
while p != self.__nil:
if p.key == key:
break
elif p.key < key:
p = p.right
else:
p = p.left
return p
def __insert_fixup(self, node:RBTNode):
"""
Insertion only violates property 2 & 4.
1. The root must be black.
2. A red node must have 2 black children.
:param node:
:return:
"""
z = node
red = RedBlackTree.RBTNode.COLOR_RED
black = RedBlackTree.RBTNode.COLOR_BLACK
while z.father.color == red: # 表明z.father.father存在
if z.father == z.father.father.left:
y = z.father.father.right # z's sibling
if y.color == red: # ---------------------------------------- case 1, y是红色
z.father.color = black
y.color = black
z.father.father.color = red
z = z.father.father
else:
if z == z.father.right: # ------------------------------------ case 2
z = z.father
self.__left_rotate(z)
# ------------------------------------------------------- case 3
z.father.color = black
z.father.father.color = red
self.__right_rotate(z.father.father)
else: # 上面三种和下面三种是对称的
y = z.father.father.left # z's sibling
if y.color == red: # ---------------------------------------- case 4
z.father.color = black
y.color = black
z.father.father.color = red
z = z.father.father
else:
if z == z.father.left: # ------------------------------------- case 5
z = z.father
self.__right_rotate(z)
# ------------------------------------------------------- case 6
z.father.color = black
z.father.father.color = red
self.__left_rotate(z.father.father)
self.__root.color = black
def __delete_fixup(self, node:RBTNode):
"""
:param node:
:return:
"""
x = node
leaf, root = self.__nil, self.__root
red, black = RedBlackTree.RBTNode.COLOR_RED, RedBlackTree.RBTNode.COLOR_BLACK
while x != root and x.color == black:
if x == x.father.left:
w = x.father.right
if w.color == red: # --------------------------------------------- case 1
w.color = black
x.father.color = red
self.__left_rotate(x.father)
w = x.father.right
if w.left.color == black and w.right.color == black: # ----------- case 2
w.color = red
x = x.father
else:
if w.right.color == black: # --------------------------------- case 3
w.left.color = black
w.color = red
self.__right_rotate(w)
w = x.father.right
w.color = x.father.color # ----------------------------------- case 4
x.father.color = black
w.right.color = black
self.__left_rotate(x.father)
x = self.__root
else:
w = x.father.left
if w.color == red:
w.color = black
x.father.color = red
self.__right_rotate(x.father)
w = x.father.left
if w.left.color == black and w.right.color == black:
w.color = red
x = x.father
else:
if w.left.color == black:
w.right.color = black
w.color = red
self.__left_rotate(w)
w = x.father.left
w.color = x.father.color
x.father.color = black
w.left.color = black
self.__right_rotate(x.father)
x = self.__root
x.color = black
@staticmethod
def make_tree(key_seq:List, val_seq:List, color_seq:List):
n = len(key_seq)
assert n >= 0 and\
n == len(val_seq) and\
n == len(color_seq)
#if n == 0:
# print("Empty seq.")
tree = RedBlackTree()
leaf = tree.__nil
nodes = [
RedBlackTree.RBTNode(key_seq[i], val_seq[i], color_seq[i])
if key_seq[i] else leaf # key_seq[i] == None --> link with leaf.
for i in range(n)
]
if n > 0:
root = tree.set_root(nodes[0])
root.father = leaf
for i in range(n):
if nodes[i] == leaf:
continue
if (i << 1) + 1 < n:
p = nodes[(i << 1) + 1]
nodes[i].left = p
if p != leaf:
p.father = nodes[i]
else:
nodes[i].left = leaf
if (i << 1) + 2 < n:
p = nodes[(i << 1) + 2]
nodes[i].right = p
if p != leaf:
p.father = nodes[i]
else:
nodes[i].right = leaf
return tree
def set_root(self, new_root:RBTNode):
assert new_root
self.__root = new_root
return self.__root
def get_level(self, node:RBTNode) -> int:
if node != self.__nil:
l, r = 0, 0
if node.left != self.__nil:
l = self.get_level(node.left)
if node.right != self.__nil:
r = self.get_level(node.right)
return 1 + max(l, r)
else:
return 0
def get_root(self) -> RBTNode:
return self.__root
def get_leaf(self) -> RBTNode:
return self.__nil
def get_inorder_seq(self):
# 把左子节点链存到st
# 那么st[-1]一定是某颗子树中最小的节点, left为叶子
# 关键在于把 L v R --> L v R v R --> ... --> v R v R ... v R
leaf = self.__nil
if self.__root == leaf:
return []
st = []
res = []
cur = self.__root
while cur != leaf or len(st) > 0: # 因为这里st只保存了左链的节点,
while cur != leaf:
st.append(cur)
cur = cur.left
p = st.pop()
res.append((p.key, p.val))
cur = p.right
return res
def is_leaf(self, node: RBTNode) -> bool:
return self.__nil == node
def is_rbt(self) -> (bool, str):
def property_4(node:RedBlackTree.RBTNode):
if node != leaf:
if node.color == red and\
(node.left.color == red or node.right.color == red):
raise RBTException(node,
"red node has at least one red child.")
else:
# may raise error
property_4(node.left)
property_4(node.right)
def property_5(node:RedBlackTree.RBTNode):
if node == leaf:
return 1
else:
l = property_5(node.left)
r = property_5(node.right)
if l != r:
raise RBTException(node, f"different black height left={l}, right={r}")
if node.color == red:
return l
else :
return l + 1
root, leaf = self.__root, self.__nil
red, black = RedBlackTree.RBTNode.COLOR_RED, RedBlackTree.RBTNode.COLOR_BLACK
if root.color == red:
return False, "error: root is red."
if leaf.color == red:
return False, "error: leaf is red."
try:
# assert that root is black and leaf is black.
property_4(self.__root)
_ = property_5(self.__root)
except RBTException as e:
return False, str(e)
return True, ""
# Return (key, val) for the first node with node.key == key.
# Else return (key, None)
def search(self, key):
p = self.__search_node(key)
if p == self.__nil:
return key, None
else:
return p.key, p.val
def insert(self, key, val):
leaf = self.__nil
node = RedBlackTree.RBTNode(key, val, RedBlackTree.RBTNode.COLOR_RED, leaf, leaf, leaf)
return self.__insert_node(node)
def delete(self, key):
p = self.__search_node(key)
if p == self.__nil:
return key, None
else:
self.__delete_node(p)
return p.key, p.val
def inorder_seq(self) -> List:
def recur(node:RedBlackTree.RBTNode, lis:List):
if node:
recur(node.left, lis)
lis.append((node.key, node.val))
recur(node.right, lis)
res = []
recur(self.__root, res)
return res
class RBTException(Exception):
def __init__(self, node:RedBlackTree.RBTNode, msg:str):
self.node = node
self.msg = msg
def __str__(self):
return "RBTException: node({})\nmsg={}".format(self.node, self.msg)
|
def merge_sort(arr:list, reverse=False):
def inner_sort(left: int, right: int, rev=False):
if left+1 < right:
mid = (left + right) >> 1
inner_sort(left, mid)
inner_sort(mid, right)
merge(tmp_list, arr, left, mid, right, reverse)
n = len(arr)
if n == 0:
return
tmp_list = arr.copy()
inner_sort(0, n, reverse)
def merge(tmp_list: list, target: list, left: int, mid:int, right: int, reverse=False):
"""
Given two sorted array [left, mid), [mid+1, right),
sort target[left, right)
"""
if left >= mid or mid >= right:
return
p, q, k = left, mid, left
while p < mid and q < right:
flag = (target[p] <= target[q]) ^ reverse
if flag:
tmp_list[k] = target[p]
p+=1
else:
tmp_list[k] = target[q]
q+=1
k += 1
st, end = p, mid
if q < right:
st, end = q, right
for i in range(st, end):
tmp_list[k] = target[i]
k+=1
for i in range(left, right):
target[i] = tmp_list[i] # cover target[left, right)
#print("l, r = ", left, right, "-"*(left+1), target[left:right])
def test_merge():
case1 = [1, 4, 6, 2, 3, 5]
tmp1 = [0] * 6
merge(tmp1, case1, 0, 3, 6)
assert case1 == [1, 2, 3, 4, 5, 6]
case1 = [1, 2]
tmp1 = [0] * 2
merge(tmp1, case1, 0, 1, 1)
assert case1 == [1, 2]
case1 = [1, 7, 9, 13, 2, 3, 4]
tmp1 = [0] * 7
merge(tmp1, case1, 0, 4, 7)
assert case1 == [1, 2, 3, 4, 7, 9, 13]
case1 = [1, 7, 9, 2, 3, 4, 13]
tmp1 = [0] * 7
merge(tmp1, case1, 0, 3, 7)
assert case1 == [1, 2, 3, 4, 7, 9, 13]
test_merge()
|
import re
def is_palindrome(text):
return processing_text(text) == processing_text(reverse(text))
def reverse(text):
return text[::-1]
def remove_punctuation(text):
return re.sub(r'[?!.\"\'\[\]();:\-\\,]', '', text)
def remove_space(text):
return text.replace(" ", "")
def low_case(text):
return text.lower()
def processing_text(text):
processed_text = low_case(remove_space(remove_punctuation(text)))
print(processed_text)
return processed_text
something = input('Enter text: ')
if is_palindrome(something):
print('Yes, it is a palindrome')
else:
print('No, it is not a palindrome')
# assert is_palindrome("Rise to Vote, Sir") is True
# assert is_palindrome("Ris..e to Vote, Sir") is True
# assert is_palindrome("A nut for a jar of tuna.") is True
|
"""
CP1404/CP5632 Practical
Demos of various os module examples
"""
import os
def main():
"""Process all subdirectories using os.walk()."""
os.chdir('Lyrics')
for directory_name, subdirectories, filenames in os.walk('.'):
print("Directory:", directory_name)
print("\tcontains subdirectories:", subdirectories)
print("\tand files:", filenames)
print("(Current working directory is: {})".format(os.getcwd()))
# renames the files as the program walks
for filename in filenames:
old_name = os.path.join(directory_name, filename)
new_name = os.path.join(directory_name, get_fixed_filename(filename))
print("Renaming {} to {}".format(old_name, new_name))
os.rename(old_name, new_name)
def get_fixed_filename(filename):
"""Return a 'fixed' version of filename."""
new_name = filename.replace(" ", "_").replace(".TXT", ".txt")
for i, current_character in enumerate(new_name):
previous_character = new_name[i - 1]
if current_character.isupper() and previous_character.islower():
new_name = new_name.replace("{}{}".format(previous_character, current_character),
"{}_{}".format(previous_character, current_character))
print(previous_character, current_character)
print(filename, new_name)
return new_name
main()
|
"""Generate random grids
"""
import networkx as nx
from .random_graph import cut_across, hidden_graph
def random_grid(side,
p_not_traversable=0.5,
n_hidden=0,
max_length=3):
""" Generate a subgraph of a grid by removing some edges and declaring other edges as hidden
Args:
side (int): The side length of the original (side x side) grid.
p_not_traversable (float, optional): The total number of edges to remove
(comprised pruned edges).
n_hidden (int, optional): The (maximal) number of hidden edges.
max_length (float, optional): The upper bound of random (uniform) weights
assigned to the edges. Should be larger than 1.
Returns:
A tuple consisting in
final graph, hidden state, source, target, cut graph and pruned graph.
"""
g = nx.grid_2d_graph(side, side)
s = list(g.nodes())[0]
t = list(g.nodes())[-1]
n_t = round(p_not_traversable * g.number_of_edges())
g, cut, pruned = cut_across(g, n_t, s, t)
g, hidden_state = hidden_graph(g, n_hidden, s=s, t=t, max_length=max_length,
weight='random')
return g, hidden_state, s, t, cut, pruned
|
from familytree import FamilyMember
def create_tree_structure():
tree_root = FamilyMember('Nancy')
tree_root.add_child('Nancy', 'Adam')
tree_root.add_child('Nancy', 'Jill')
tree_root.add_child('Nancy', 'Carl')
tree_root.add_child('Carl', 'Catherine')
tree_root.add_child('Carl', 'Joseph')
tree_root.add_child('Jill', 'Kevin')
tree_root.add_child('Kevin', 'Samuel')
tree_root.add_child('Kevin', 'George')
tree_root.add_child('Kevin', 'James')
tree_root.add_child('Kevin', 'Aaron')
tree_root.add_child('James', 'Mary')
tree_root.add_child('George', 'Patrick')
tree_root.add_child('George', 'Robert')
return tree_root
if __name__ == '__main__':
mytree = create_tree_structure()
print("Kevin's grandparent:")
print(mytree.find_grandparent('Kevin'))
print("Family members without siblings:")
mytree.has_no_siblings()
print("Family members without children:")
mytree.has_no_children()
|
file = open ("words.txt")
required = input ("Enter the alphabet:")
def uses_all(words, required):
for letters in required:
if letters not in words:
return False
return True
count = 0
tcount = 0
for line in file:
tcount += 1
words = line.strip()
if uses_all(words, required) == True:
count += 1
print (words)
diff = tcount - count
print ("Total words in file is: ",tcount)
print ("Total words containing the letter is: ",count)
print ("Difference is ",diff)
|
file = open("words.txt")
def avoids (words,forbidden):
for letter in words:
if letter in forbidden:
return False
return True
forbidden = input ("Enter letter not to apprear: ")
count = 0
wordcount = 0
for lines in file:
words = lines.strip()
wordcount +=1
if avoids(words, forbidden) == True:
count += 1
print (words)
print ("Total count:",count)
print ("Total word count:", wordcount)
difference = wordcount - count
print ("Difference is : ",difference)
|
import math
"""Area of a square"""
a = int (input("Enter the side for square's area:"))
b = int (input("Enter the radius for circle's area:"))
c = int (input("Enter the radius for sphere's area:"))
def area_square(side):
area_square = side * side
return area_square
"""Area of a circle"""
def area_circle(radius):
area_circle = (2*math.pi*radius)
return area_circle
"""Area of a sphere"""
def area_sphere(radius):
area_sphere = ((4/3)*math.pi*(radius**2))
return area_sphere
print ("Square :",area_square(a))
print ("Circle :",area_circle(b))
print ("Sphere :",area_sphere(c))
|
class point:
"""this is a point class"""
def __init__(self,x,y):
"""constructor for point"""
self.x = x
self.y = y
def __str__(self):
return ("The point is" + str (self.x) + "," + str (self.y))
def __add__(self,other):
my_point = point (self.x+other.x,self.y+other.y)
return (my_point)
p1 = point (5,2)
p2 = point (10,10)
p3 = p1 + p2
p4 = p3 + p1
print (p4)
|
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName('SparkByExamples.com').getOrCreate()
data = ["Project Gutenberg’s",
"Alice’s Adventures in Wonderland",
"Project Gutenberg’s",
"Adventures in Wonderland",
"Project Gutenberg’s"]
rdd = spark.sparkContext.parallelize(data)
for element in rdd.collect():
print(element)
# Flatmap
rdd2 = rdd.flatMap(lambda x: x.split(" "))
for element in rdd2.collect():
print(element)
|
import math
def binary_numbers(a):
alist = []
digits = a
numbers = 2**digits-1
for i in range(numbers+1):
a = list(bin(i))
a = a[2:][::-1]
for i in range(digits-len(a)):
a.append(0)
for i in range(len(a)):
a[i] = int(a[i])
alist.append(a[::-1])
for i in alist:
for j in range(len(i)):
if i[j] == 0:
i[j] = -1
return alist
def make_string(entry):
b = [str(i) for i in entry]
return " ".join(b)
def permutation(array):
i = len(array) - 1
j = i
while array[i-1] > array[i]:
i -= 1
if i <= 0:
return False
while (array[j] <= array[i-1]) and j >= i:
j -= 1
array[i-1], array[j] = array[j], array[i-1]
array[i:] = array[i:][::-1]
return array
def rosalind_output(length):
array = [i for i in range(1,length+1)]
number_arrangements = math.factorial(len(array))
print number_arrangements*2**length
negative_array(array, my_binaries)
for i in range(number_arrangements-1):
array = permutation(array)
negative_array(array, my_binaries)
def negative_array(array, bin_numbers):
for i in range(len(bin_numbers)):
current = []
for j in range(len(bin_numbers[i])):
current.append(bin_numbers[i][j]*array[j])
current = make_string(current)
print current
def main(number):
my_binaries = binary_numbers(number)
rosalind_output(number)
number = 2
my_binaries = binary_numbers(number)
rosalind_output(number)
|
def eat_junk(food):
assert food in ["pizza", "shaworma", "ice_cream"] , "food must be junk food"
return f"NOM NOM NOM I am eatin {food}"
food = input("enter a food please:")
print(eat_junk(food))
def add(a,b):
"""
>>> add (2,3)
5
>>> add(100 ,200)
300
"""
return a+b
with open("novel.txt", "w") as file:
file.write("Muahahhah")
|
def square_of_6():
return 6**2
result = square_of_6()
print(result)
from random import random
def flip_coin():
r=random()
if r>0.5:
return "Heads"
else:
return "Tails"
print(flip_coin())
def square(num):
return num*num
print(square(5))
print(square(2))
def number_default(num, power=2):
return num ** power
print(number_default(2,3))
print(number_default(3))
def full_name(first="Colt" , last="Stell"):
return "Your name is {first} {last}"
print(full_name() )
intstructor="colt"
def hello():
return f"Hello {intstructor}"
print(hello())
total= 0
def hole():
global total
total +=1
return total
print(hole())
def return_day(num):
days=["luni","marti","miercuri", "joi","vineri","sambata","duminica"]
if num >0 and num <= len(days):
return days[num-1]
return None
print(return_day(2))
l1=["mama","tata"]
l2=["mama","anca"]
def intersection(l1, l2):
return[val for val in l1 if val in l2]
print(intersection(l1,l2))
def nums_ad(*nums):
total=0
for val in nums:
total +=val
return total
print(nums_ad(1,1,2,2,3,4,5,6))
print(nums_ad(1,2)) |
from datetime import *
def diffDate(x):
x = x.split('-')
tgl= date(int(x[0]),int(x[1]),int(x[2]))
datenow = datetime.date(datetime.now())
result = tgl - datenow
result = result.days
print("Tanggal sekarang : ",datenow)
print("Tanggal yang diminta : ",tgl)
print("Selisih :", result, "hari")
return result
diffDate('2021-12-31')
|
cake = input("Do you want cake? (yes or no)")
if cake == "yes" or cake == "Yes" or cake == "y":
print("have some cake")
elif cake == "no" or cake == "No" or cake == "n" :
print("no cake for you!!!")
else:
print("Nope: sorry, I dont understand")
|
import random
"""
3.6
3.08
3.092
3.142
3.1422
3.141512
3.1401636
3.14184416 10^8 losowan
"""
def in_circle(x, y):
return x ** 2 + y ** 2 < 1
def calc_pi(n=100):
inside_count = 0
for _ in range(n):
if in_circle(random.random(), random.random()):
inside_count += 1
pi = (inside_count / float(n)) * 4
print (pi)
calc_pi(10)
calc_pi(10**2)
calc_pi(10**3)
calc_pi(10**4)
calc_pi(10**5)
calc_pi(10**6)
calc_pi(10**7)
calc_pi(10**8)
|
import random
import math
import cmath
def swap(L, left, right):
"""Zamiana miejscami dwoch elementow na liscie."""
item = L[left]
L[left] = L[right]
L[right] = item
def random_list(size, maxVal):
return [random.randint(0,maxVal) for r in range(size)]
def nearly_sorted(size, maxVal):
L = [random.randint(0,maxVal) for r in range(size)]
print(L)
for i in range(0,int(size/2)):
k = i
for j in range(i+1, size):
if L[j] < L[k]:
k = j
swap(L, i, k)
return L
def reverse_nearly_sorted(size, maxVal):
L = [random.randint(0,maxVal) for r in range(size)]
print(L)
for i in range(0,int(size/2)):
k = i
for j in range(i+1, size):
if L[j] > L[k]:
k = j
swap(L, i, k)
return L
def gauss_random(size):
L = [int(random.gauss(0,1)) for r in range(size)]
return L
def random2(size):
L = [random.randint(0,int(math.sqrt(size))) for r in range(size)]
return L
|
"""Iterator Pattern"""
"""
迭代器模式(Iterator Pattern)是 Java 和 .Net 编程环境中非常常用的设计模式。
这种模式用于顺序访问集合对象的元素,不需要知道集合对象的底层表示。
"""
"""
意图:
提供一种方法 -> 顺序访问一个聚合对象中各个元素, 而又无须暴露该对象的内部表示。
主要解决:不同的方式来遍历整个整合对象。
何时使用:遍历一个聚合对象。
如何解决:把在元素之间游走的责任交给迭代器,而不是聚合对象。
关键代码:定义接口:hasNext, next。
应用实例:
JAVA 中的 iterator。
PYTHON for
优点:
1、它支持以不同的方式遍历一个聚合对象。
2、迭代器简化了聚合类。
3、在同一个聚合上可以有多个遍历。
4、在迭代器模式中,增加新的聚合类和迭代器类都很方便,无须修改原有代码。
缺点:
由于迭代器模式将存储数据和遍历数据的职责分离,
增加新的聚合类需要对应增加新的迭代器类,类的个数成对增加,这在一定程度上增加了系统的复杂性。
使用场景:
1、访问一个聚合对象的内容而无须暴露它的内部表示。
2、需要为聚合对象提供多种遍历方式。
3、为遍历不同的聚合结构提供一个统一的接口。
注意事项:
迭代器模式就是分离了集合对象的遍历行为,
抽象出一个迭代器类来负责,
这样既可以做到不暴露集合的内部结构,又可让外部代码透明地访问集合内部的数据。
"""
"""
1. 创建一个迭代器方法的Iterator接口
2. 返回一个迭代器的Container接口
3. 实现Container接口的实体类将负责Iterator接口
"""
class A(object):
def __init__(self, num):
self.num = num
self.start_num = -1
def __iter__(self):
'''
@summary: 迭代器,生成迭代对象时调用,返回值必须是对象自己,然后for可以循环调用next方法
'''
return self
def __next__(self):
'''
@summary: 每一次for循环都调用该方法(必须存在)
'''
self.start_num += 1
if self.start_num >= self.num:
raise StopIteration()
return self.start_num
if __name__ == "__main__":
for i in A(10):
print(i) |
class Node:
def __init__(self, data,next=None,previous=None,child=None):
self.data = data
self.next = next
self.previous = previous
self.child = child
def printListRecursive(head, level=0):
aux = head
while aux is not None:
print " "*level + aux.data
if aux.child is not None:
printListRecursive(aux.child, level + 4)
aux = aux.next
def printList(head):
aux = head
while aux is not None:
print "%s " % aux.data
aux = aux.next
def flatList(head, tail):
assert head is not None, tail is not None
aux=head
while aux is not None:
if aux.child is not None:
tail = appendChild(tail,aux.child)
aux = aux.next
def appendChild(tail, child):
assert tail is not None
tail.next,child.previous = child,tail
tail = child
while tail.next is not None: tail = tail.next
return tail
def unflatList(head):
assert head is not None
aux = head
while aux is not None:
if aux.child is not None:
aux.child.previous.next = None
aux.child.previous = None
unflatList(aux.child)
aux = aux.next
if __name__ == "__main__":
a = Node("a")
a1 = Node("a1")
a2 = Node("a2")
a.child,a1.next,a2.previous = a1,a2,a1
a21 = Node("a21")
a22 = Node("a22")
a2.child, a21.next, a22.previous = a21,a22,a21
b = Node("b")
b1 = Node("b1")
b2 = Node("b2")
b.child,b1.next,b2.previous = b1,b2,b1
a.next,b.previous = b,a
flatList(a,b)
printList(a)
unflatList(a)
printListRecursive(a)
|
import time
# Square of Sum
def sq_o_sm(n):
start = time.time()
sum_10 = 55
for i in range(1,n//10):
new_sum = int(str(i)+"00")+55
sum_10+=new_sum
square_of_sum = sum_10**2
return square_of_sum,start
square_of_sum,time_tkn = sq_o_sm(100)
print("Time taken: {} milliseconds".format((time.time()-time_tkn)*1000))
print(square_of_sum)
# Sum of Square
def sm_o_sq(n):
start = time.time()
sum_Sq = 385
for j in range(11,n+1):
sum_Sq+=j**2
return sum_Sq,start
Sum_of_square, time_taken = sm_o_sq(100)
print("Time taken: {} milliseconds".format((time.time()-time_taken)*1000))
print(Sum_of_square)
# Difference
print(square_of_sum - Sum_of_square)
# 25164150
|
from math import pi
from time import sleep
#Problem 1 - Count even integers in list
def count_evens(L):
count = 0
for i in L:
if i % 2 == 0:
count+=1
return count
#Problem 2 - List to string without str(list)
def list_to_str(lis, separator=', '):
#List start
s = "["
#Items 0 to len-1 (with separator)
for i in range(0,len(lis)-1):
s += str(lis[i])
s += separator
#Final item (no separator)
s+= str(lis[-1])
s+= "]"
return s
#Problem 3 - List comparison without list1 == list2 (instead by element)
def lists_are_the_same(list1, list2):
if len(list1) != len(list2):
return False
for i in range(0, len(list1)):
if(list1[i] is not list2[i]):
return False
return True
#Problem 4 - Sexy recursive GCF
steps = 0
def simplify_fraction(n, m, start=2):
global steps
start = min(start,2)
#Divisor cannot be 1 (short circuit) or larger than the smaller of the denominator or numerator (inclusive)
for div in range(start, min(n,m)+1):
if(n % div == 0 and m % div == 0):
n = int(n/div)
m = int(m/div)
# print("{}: {}/{}".format(div,n,m))
return simplify_fraction(n,m,div)
steps+=1
result = (n,m,steps)
steps = 0
return result
#Problem 5 - Leibniz formula for π
def leibniz(n):
total = 0
for k in range(n):
total += 4*((-1)**k)/(2*k+1)
# print("{}: {}".format(k, 4*total))
return total
#Truncates float i to n digits
def truncate(i, n):
return int(i*10**n)/10**n
#How many digits of π is a number accurate to?
def accuracy(lpi):
n = 0
while(True):
npi = truncate(pi, n)
nlpi = truncate(lpi, n)
if(npi == nlpi):
n+=1
else:
return n
#How many iterations of the Leibniz summation for π does it take for the approximation to be accurate to some number of digits?
def toAccuracy(target):
k=0
lpi = 4
acc = 0
while(acc < target):
k+=1
lpi += 4*((-1)**k)/(2*k+1)
acc = accuracy(lpi)
return k
#Same as above, skips the first 10^(n-1) iterations
def toAccuracyFaster(target):
k=10**(target-1) #Leibniz steps
lpi = leibniz(k) #Let's get like 10^target-1 out of the way
acc = accuracy(lpi)
while(acc < target):
lpi += 4*((-1)**k)/(2*k+1)
k+=1
acc = accuracy(lpi)
return k
#Problem 6
esteps = 0
def euclid(a,b):
global esteps
if(a%b==0):
result = (b,esteps)
esteps = 0
return result
esteps += 1
return euclid(b,a%b)
if __name__ == "__main__":
#Testing
lis = [1,2,3,4,5,6]
print("Problem 1: There are {} even numbers in {}.".format(count_evens(lis), lis))
print("Problem 2: {}.".format(list_to_str(lis)))
print("Problem 3 (1): {} == {}? {}".format(lis, lis, lists_are_the_same(lis, lis)))
lis2 = [2,2,3,9,5,6]
print("Problem 3 (2): {} == {}? {}".format(lis, lis2, lists_are_the_same(lis, lis2)))
fraction = (2322,654)
simp = simplify_fraction(*fraction) #3/13 * [3,3,3,5,17]
print("Problem 4 (1): {}/{} simplifies to {}/{} in {} steps using a recursive method.".format(*fraction, *simp))
esimp = euclid(*fraction)
print("Leibniz approx takes {} steps".format(toAccuracy(5)))
print("Problem 6 (2): \na) GCF of {} and {}: {} in {} steps using Euclid's algorithm.".format(*fraction, *esimp))
print("b) {}/{} simplifies to {}/{}".format(*fraction, *[int(x/esimp[0]) for x in fraction]))
# Uncomment for continuous Leibniz step-accuracy generation
# n=1
# while True:
# print(toAccuracyFaster(n))
# n+=1 |
#-------------------------------------------------------------------------------
# Name: quickSort.py
# Purpose: Implementing the quickSort algorithm for different values of pivot.
#
# Author: Denado Rabeli
#
# Created: 12/06/2020
# Copyright: (c) denad 2020
# Licence: <your licence>
#-------------------------------------------------------------------------------
import random
import time
#To create a random array
def createRandArray(n):
A=[random.randint(0,100) for i in range(n)]
return A
#defining the partition starting from the left most number
def partitionL(array, start, end):
pivot = array[start]
low = start + 1
high = end
while True:
# If the current value we're looking at is larger than the pivot
# it's in the right place (right side of pivot) and we can move left,
# to the next element.
# We also need to make sure we haven't surpassed the low pointer, since that
# indicates we have already moved all the elements to their correct side of the pivot
while low <= high and array[high] >= pivot:
high = high - 1
# Opposite process of the one above
while low <= high and array[low] <= pivot:
low = low + 1
# We either found a value for both high and low that is out of order
# or low is higher than high, in which case we exit the loop
if low <= high:
array[low], array[high] = array[high], array[low]
# The loop continues
else:
# We exit out of the loop
break
array[start], array[high] = array[high], array[start]
return high
def quick_sortL(array, start, end):
if start >= end:
return
#call partition for the entire array
p = partitionL(array, start, end)
#after finding partition , run quickSort again for the part left of partition
#and for the part on the right of partition
quick_sortL(array, start, p-1)
quick_sortL(array, p+1, end)
a=createRandArray(100)
#To get the running time we substract start from end (we also substract 1 because of sleep function.)
start=time.time()
quick_sortL(a,0,len(a)-1)
time.sleep(1)
end=time.time()
print("After left most pivot Sort:")
print("The running time was : {:f}".format(end-start-1))
def partitionR(array, start, end):
#First we get a random position for pivot then replace it
#at the beggining and call partition left
randpivot = random.randint(start,end)
array[start],array[randpivot]=array[randpivot],array[start]
return partitionL(array,start,end)
def quick_sortR(array, start, end):
if start >= end:
return
p = partitionR(array, start, end)
quick_sortR(array, start, p-1)
quick_sortR(array, p+1, end)
a=createRandArray(100)
start=time.time()
quick_sortR(a,0,len(a)-1)
time.sleep(1)
end=time.time()
print("After random pivot Sort:")
print("The running time was : {:f}".format(end-start-1))
def partitionM(array, start, end):
#We get the middle position and replace it with the first one , then run
#partitioning.
midpivot = (start+end)//2
array[start],array[midpivot]=array[midpivot],array[start]
return partitionL(array,start,end)
def quick_sortM(array, start, end):
if start >= end:
return
p = partitionM(array, start, end)
quick_sortM(array, start, p-1)
quick_sortM(array, p+1, end)
a=createRandArray(100)
start=time.time()
quick_sortM(a,0,len(a)-1)
time.sleep(1)
end=time.time()
print("After middle pivot Sort:")
print("The running time was : {:f}".format(end-start-1))
'''
For input of size 100 :
The running time for left most was : 0.009998
The running time for random was : 0.009999
The running time for middle was : 0.006826
For input of size 1000:
The running time for left most was : 0.010000
The running time for random was : 0.000139
The running time for middle was : 0.000109
For input of size 10000:
The running time for left most was : 0.080212
The running time for random was : 0.119965
The running time for middle was : 0.080191
For input of size 100000:
The running time for left most was : 1.306391
The running time for random was : 1.372120
The running time for middle was : 1.288913
For further bigger inputs the maximum recursion depth was exceeded .
As far as comparison is concerned we can see that the left most one was the most
stable one with the time going up the bigger the input .
The random one was the most unstable with the running time going up and down in
an unpredictable manner.
The middle pivot was the most efficient choice for this algorithm,
although a little unpredictable at times too.
''' |
#-------------------------------------------------------------------------------
# Name: Shopping List (Summative)
# Purpose:
#
# Author: Ryelee McCoy
#
# Created: 11/10/2019
# Copyright: (c) ryelee.mccoy 2019
# Licence: <your licence>
#-------------------------------------------------------------------------------
shoplist = {}
def setup():
addlist = True
while addlist == True:
shopping = input(str("What do you need at the store today? type done when you have everything "))
if shopping == "done":
addlist = False
else:
cost = float(input("What is the cost of that item? " ))
shoplist[shopping] = cost
dellist = True
while dellist == True:
print(shoplist)
pick = input(str("Type remove if you have to remove an item or type change if you have to change the cost of an item or type done if everything is correct "))
if pick == "remove" :
pickremove = input(str("Which item do you want to remove? "))
del shoplist[pickremove]
elif pick == "change":
pickchange = input(str("What item do you need to change? "))
costchange = float(input("What is the cost of the item? "))
shoplist[pickchange] = costchange
elif pick == "done":
dellist = False
else:
print("Thats not a option sorry try again!")
totalcost = sum(shoplist.values())
print(shoplist)
print("Your total cost is", totalcost)
setup() |
#!/usr/bin/python
class Heap:
def __init__(self, a):
self.a = a
self.size = len(a)
def max_heapify(self, i):
while 1:
l = i * 2 + 1
r = i * 2 + 2
largest = i
if l < self.size and self.a[l] > self.a[i]:
largest = l
if r < self.size and self.a[r] > self.a[largest]:
largest = r
if largest != i:
self.a[i], self.a[largest] = self.a[largest], self.a[i]
i = largest
else:
break
def build_max_heap(self):
for i in range(len(self.a)/2-1, -1, -1):
self.max_heapify(i)
def heapsort(self):
self.build_max_heap()
for i in range(len(self.a)-1, 0, -1):
self.a[0], self.a[i] = self.a[i], self.a[0]
self.size -= 1
self.max_heapify(0)
if __name__ == '__main__':
heap = Heap([16,4,10,14,7,9,3,2,8,1])
heap.max_heapify(1)
print heap.a
heap = Heap([1,2,3,4,5,6,7])
heap.build_max_heap()
print heap.a
heap = Heap([4,1,3,2,16,9,10,14,8,7])
heap.heapsort()
print heap.a
import random
a = [random.randrange(10000) for i in range(100000)]
heap = Heap(a)
heap.heapsort()
|
#!/usr/bin/env python
import random
def random_sampling_no_duplicate(a, n):
for i in range(n):
index = random.randint(i,len(a)-1)
a[i],a[index] = a[index],a[i]
return a[:n]
def random_sampling_with_duplicate(a, n):
result = []
for i in range(n):
index = random.randint(0,len(a)-1)
result.append(a[index])
return result
if __name__ == '__main__':
print random_sampling_no_duplicate(range(20), 10)
print random_sampling_with_duplicate(range(20), 10)
|
##############################################################
# server.py
# Part of UnSH, and insecure protocol to connect devices.
#
# Michael Yoder
# v. 1.0
##############################################################
import socket
import os
import sys
import subprocess
import struct
HOST = ''
'''
Command line arguments.
Default to port 5000
'''
if '-p' in sys.argv:
try:
PORT = int(sys.argv[sys.argv.index('-p') + 1])
except:
print "Invalid port input"
PORT = 5000
else:
PORT = 5000
'''
This is the server side function to send data from server->client.
A file name is given, and an 8 byte header is appended to a string
representing that file.
RETURN: A string representation of a file with an 8 byte header
packaged in a struct.
'''
def grab(file_name):
read_file = open(file_name, "rb")
file_string = read_file.read()
read_file.close()
file_size = len(file_string)
return struct.pack('>Q', file_size) + file_string
'''
the server side function to receive a file. a socket object
is passed in, and the first 8 bytes are read, denoting the file
size. the rest of the file is then read in based on the length.
return: a string object representing a file.
'''
def get_file(sock):
full_message = recvall(sock, 8)
print full_message
if not full_message:
return None
mess_length = struct.unpack('>Q', full_message)[0]
return recvall(sock, mess_length)
'''
A function which takes a number of bytes, and continue to receive
data until that number of bytes has been received.
RETURN: The data received, None if the string ended early.
'''
def recvall(sock, n):
dat = ''
while len(dat) < n:
piece = sock.recv(n - len(dat))
if not piece:
return None
dat += piece
return dat
'''
Takes a host and a port and accepts one connection.
RETURN: A socket object with a connection.
'''
def open_connection(host, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
return s, conn, addr
'''
The main code loop. Receives data, makes a system call
or a "grab"/"put" command. Sends data back. Upon
receiving an "exit" command, the program is stopped.
If the client disconnects with no "exit", the server accepts
another connection.
'''
if __name__ == "__main__":
s, conn, addr = open_connection(HOST, PORT)
conn.sendall('Connection established.')
while 1:
data = conn.recv(1024)
if not data:
conn, addr = s.accept()
if data == "exit":
conn.sendall(data)
break
try:
if data.split()[0] == "grab":
out = grab(data.split()[1])
elif data.split()[0] == "put":
message = get_file(conn)
open(data.split()[1], "wb").write(message)
out = 'Success'
else:
out = subprocess.check_output(data, stderr=subprocess.STDOUT, shell=True)
if not out:
out = "Done."
if data.split()[0] == "cd":
os.chdir(data.split()[1])
except Exception, e:
out = str(e)
conn.sendall(out)
conn.close()
|
from tkinter import *
def sum():
r.set(float(n1.get()) + float(n2.get()))
def subtraction():
r.set(float(n1.get()) + float(n2.get()))
def multiplication():
r.set(float(n1.get()) + float(n2.get()))
root = Tk()
root.config(bd=15)
n1 = StringVar()
n2 = StringVar()
r = StringVar()
Label(root, text="Num 1").pack()
Entry(root, justify="center", textvariable=n1).pack()
Label(root, text="Num 2").pack()
Entry(root, justify="center", textvariable=n2).pack()
Label(root, text="\nResult").pack()
Entry(root, justify="center", textvariable=r, state="disabled").pack()
Label(root, text="").pack()
Button(root, text="Sum", command=sum).pack(side="left")
Button(root, text="Subtraction", command=subtraction).pack(side="left")
Button(root, text="Multiplication", command=multiplication).pack(side="left")
root.mainloop()
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.