text
stringlengths 37
1.41M
|
---|
# Dado um número inteiro n ≥ 0, calcular o fatorial de n (n!). Outra maneira
def main():
n = int(input("Digite o valor de n: "))
# inicia as variáveis
fat, i = 1, 2
while i <= n:
fat *= i
i += 1
# resultado
print("O valor de %d! eh =" %n, fat)
#--------------------------------------------
main()
|
# Dado n > 0, inteiro e x real (float), calcular x + xˆ3/ 3 + xˆ5/ 5 + . . . + xˆ2n-1/ (2n-1)
def soma_serie_1():
#ler n inteiro > 0
n = int(input("Digite o valor de n > 0 inteiro: "))
#ler o x float
x = float(input("Digite o valor de x: "))
#inicia a soma
soma = 0
#variar k de 1 até n e somar cada termo
for k in range (1, n+1):
soma = soma + pow(x, 2*k-1)/(2*k-1) #também poderia ser escrito como soma + (x**(2*k-1))/(2*k-1)
#imprime o resultado
print ("O valor da soma é:", soma)
soma_serie_1()
|
# Dados 3 números imprimi-los em ordem crescente.
# Considere ordem crescente quando for menor ou igual ao seguinte.
a = int(input("Digite o primeiro número: "))
b = int(input("Digite o segundo número: "))
c = int(input("Digite o terceiro número: "))
if a >= b >= c:
print(c, b, a)
elif a >= c >= b:
print(b, c, a)
elif b >= a >= c:
print(c, a, b)
elif b >= c >= a:
print(a, c, b)
elif c >= a >= b:
print(b, a, c)
elif c >= b >= a:
print(a, b, c)
|
# Escreva a função VerificaLC(MAT, N, M) que verifica se a matriz MAT de N linhas por M colunas
# possui 2 linhas ou 2 colunas iguais, devolvendo True ou False.
MAT = [[1, 1, 3], [1, 2, 3], [1, 4, 3], [2, 1, 3]]
def VerificaLC(MAT, N, M):
for j in range(N):
for k in range(j + 1, N):
if compara_linhas(MAT, j, k, M) == True:
return True
break
for i in range(M - 1):
for j in range(1, M):
if compara_colunas(MAT, i, j, N) == True:
return True
return False
def compara_colunas(mat, C1, C2, N):
for j in range(N):
if mat[j][C1] != mat[j][C2]:
return False
break
return True
def compara_linhas(mat, L1, L2, m):
if mat[L1] == mat[L2]:
return True
else: return False
print(VerificaLC(MAT, 4, 2))
|
# Dado n ≥ 0, imprimir separadamente cada um dos dígitos de N na ordem direta
def main ():
#leia o número
n = int(input("Digite um número: "))
rev = 0
dir = 0
while n > 0:
digito = n % 10
rev = rev*10 + digito
n = n // 10
while rev > 0:
dig = rev % 10
dir = dir*10 + dig
print (dig)
rev = rev // 10
main()
|
#Função mult_pol(a, b) que devolve lista contendo o produto dos polinômios a e b
a = [1,1,3,4]
b = [2,2]
def mult_pol(a,b):
res = [0]*(len(a)+len(b)-1) #cria o tamanho do polinomio resultante
for c1,i1 in enumerate(a): #o c1 serve como base pra saber o indice do X, o i1 é o elemento que vai ser multiplicado
for c2,i2 in enumerate(b): #o c2 serve como base pra saber o indice do X, o i2 é o elemento que vai ser multiplicado
res[c1+c2] += i1*i2 #c1+c2 = indice do X / i1*i2 é a multiplicação dos elementos
return res
print (mult_pol(a,b))
|
# Dados N > 0 verificar se N é palíndrome. Um número é palíndrome quando é o mesmo lido da direita
# para a esquerda ou da esquerda para a direita. Ou seja, o primeiro algarismo é igual ao último, o segundo igual
# ao penúltimo e assim por diante
def main ():
n = int(input("Digite um número para verificar se ele é palíndrome: "))
temp = n
reverso = 0
while n > 0:
dig = n%10
reverso = reverso*10 + dig
n = n//10
if temp == reverso:
print ("O número", temp, "é palíndrome.")
else: print ("O número", temp, "não é palíndrome.")
main ()
|
lista = [1,2,3]
string = ''
for elemento in lista:
string = string + '//' + str(elemento)
print(string)
print(string.split('//')[1:])
|
#!/usr/bin/env python3
from pprint import pprint
import networkx as nx
import numpy as np
from utils import d, w, print_wd
from structures import MyTuple
def cp(g, return_delta=False):
"""
Compute the clock period of a synchronous circuit.
+------------------+------------------+
| Time complexity | :math:`O(E)` |
+------------------+------------------+
| Space complexity | :math:`O(V + E)` |
+------------------+------------------+
:param g: A NetworkX (Multi)DiGraph representing a synchronous circuit.
:param return_delta: Whether to return the computed :math:`\Delta` or not (used in other algorithms).
:return: The clock period of the given circuit.
"""
# STEP 1
# Let G0 be the sub-graph of G that contains precisely those edges e with register count w(e) = 0.
zero_edges = list(filter(lambda e: w(g, e) == 0, g.edges))
g0 = nx.MultiDiGraph()
g0.add_nodes_from(g.nodes(data=True))
g0.add_edges_from(zero_edges)
delta = dict()
# STEP 2
# By condition W2, G0 is acyclic. Perform a topological sort on G0, totally ordering its vertices so that if there
# is an edge from vertex u to vertex v in G0, then u precedes v in the total order. Go though the vertices in the
# order defined by the topological sort.
for v in nx.topological_sort(g0): # O(V + E)
# STEP 3
# On visiting each vertex v, compute the quantity delta(v) as follows:
# a. If there is no incoming edge to v, set delta(v) <- d(v).
# b. Otherwise, set delta(v) <- d(v) + max { delta(u) : u -e-> v and w(e) = 0 }.
delta[v] = d(g0, v)
if g0.in_degree(v) > 0:
delta[v] += max(list(map(lambda e: delta[e[0]], g0.in_edges(v))))
# STEP 4
# The clock period is max { delta(v) }.
if return_delta:
return max(delta.values()), delta
return max(delta.values())
def wd(g, show=False):
"""
Given a synchronous circuit :math:`G`, this algorithm computes :math:`W(u, v)` and :math:`D(u, v)` for all
:math:`u,v \in V` such that :math:`u` is connected to :math:`v` in :math:`G`.
+------------------+----------------+
| Time complexity | :math:`O(V^3)` |
+------------------+----------------+
| Space complexity | :math:`O(V^2)` |
+------------------+----------------+
:param g: A NetworkX (Multi)DiGraph representing a synchronous circuit.
:param show: Print the matrices.
:return: Matrices W and D in the form ``dict<(u,v), int>``.
"""
# STEP 1
# Weight each edge (u,?) in E with the ordered pair (w(e), -d(u)).
g = g.copy()
for e in g.edges:
g.edges[e]['weight'] = MyTuple((w(g, e), -d(g, e[0])))
# STEP 2
# Using the weighting from Step 1, compute the weight of the shortest path joining each connected pair of vertices
# by solving an all-pairs shortest-paths algorithm -- Floyd-Warshall.
# In the all-pairs algorithm, add two weights by performing component-wise addition, and compare weights using
# lexicographic ordering.
sp = nx.floyd_warshall(g) # O(V^2)
for u in sp:
for v in sp[u]:
if sp[u][v] == 0:
sp[u][v] = MyTuple((0, 0))
# STEP 3
# For each shortest path weight (x, y) between two vertices u and v, set W(u, v) <- x and D(u, v) <- d(v) - y.
W = {(u, v): sp[u][v][0] for u in g.nodes for v in g.nodes if sp[u][v] != np.inf}
D = {(u, v): d(g, v) - sp[u][v][1] for u in g.nodes for v in g.nodes if sp[u][v] != np.inf}
if show:
print('Matrix W')
print_wd(W)
print('Matrix D')
print_wd(D)
return W, D
def retime(g, r):
"""
Compute the retimed graph.
:param g: A NetworkX (Multi)DiGraph representing a synchronous circuit.
:param r: The retiming function :math:`r: V \mapsto Z` to be applied.
:return: The retimed graph.
"""
gr = g.copy()
for e in gr.edges:
gr.edges[e]['weight'] = gr.edges[e]['weight'] + r[e[1]] - r[e[0]]
return gr
def __binary_search(arr, f, g):
"""
Perform the binary search in order to find the minimum feasible value of ``c`` inside ``arr``.
:param arr: The array on which to perform the binary search.
:param f: Function to be applied to ``g`` and ``arr[mid]`` (``check_th7`` or ``feas``).
:param g: A NetworkX (Multi)DiGraph representing a synchronous circuit.
:return: The minimum clock period and the corresponding retiming function.
"""
def bs_rec(low, high, prev_mid=None, prev_x=None):
if high >= low:
mid = (high + low) // 2
x = f(g, arr[mid])
if x is None:
return bs_rec(mid+1, high, prev_mid, prev_x)
else:
return bs_rec(low, mid-1, mid, x)
else:
return arr[prev_mid], prev_x
return bs_rec(0, len(arr)-1)
def opt1(g, show_wd=False):
"""
Given a synchronous circuit :math:`G`, this algorithm determines a retiming :math:`r` such that the clock period of
:math:`G_r` is as small as possible.
+------------------+-----------------------+
| Time complexity | :math:`O(V^3 \log V)` |
+------------------+-----------------------+
| Space complexity | :math:`O(V^2)` |
+------------------+-----------------------+
:param g: A NetworkX (Multi)DiGraph representing a synchronous circuit.
:param show_wd: Print matrices W and D.
:return: The retimed graph having the smallest possible clock period.
"""
# STEP 1
# Compute W and D using Algorithm WD.
W, D = wd(g, show=show_wd)
# STEP 2
# Sort the elements in the range of D.
D_range = np.unique(list(D.values()))
D_range.sort()
def check_th7(g, c): # O(V^3)
bfg = nx.MultiDiGraph()
bfg.add_weighted_edges_from([(e[1], e[0], w(g, e)) for e in g.edges])
bfg.add_weighted_edges_from([(v, u, W[u, v]-1)
for u in g.nodes for v in g.nodes
if (u, v) in W and (u, v) in D and
D[u, v] > c and not (D[u, v] - d(g, v) > c or D[u, v] - d(g, u) > c)])
root = 'root'
bfg.add_weighted_edges_from([(root, n, 0) for n in bfg.nodes])
try:
return nx.single_source_bellman_ford_path_length(bfg, root)
except nx.exception.NetworkXUnbounded:
return None
# STEP 3
# Binary search among the elements D(u, v) for the minimum achievable clock period. To test whether each potential
# clock period c is feasible, apply the Bellman-Ford algorithm to determine whether the condition in Theorem 7
# can be satisfied.
clock, r = __binary_search(D_range, check_th7, g)
# STEP 4
# For the minimum achievable clock period found in Step 3, use the values for the r(v) found by the Bellman-Ford
# algorithm as the optimal retiming.
return retime(g, r)
def feas(g, c):
"""
Given a synchronous circuit :math:`G` and a desired clock period :math:`c`, this algorithm produces a retiming
:math:`r` of :math:`G` such that :math:`G_r` is a synchronous circuit with clock period not greater than :math:`c`,
if such retiming exists.
+------------------+------------------+
| Time complexity | :math:`O(VE)` |
+------------------+------------------+
| Space complexity | :math:`O(V + E)` |
+------------------+------------------+
:param g: A NetworkX (Multi)DiGraph representing a synchronous circuit.
:param c: The desired clock period.
:return: The retiming function or ``None`` if ``c`` is not feasible.
"""
# STEP 1
# For each vertex v, set r(v) <- 0.
r = {v: 0 for v in g.nodes}
# STEP 2
# Repeat |V| - 1 times.
gr = None
for _ in range(g.number_of_nodes() - 1):
# STEP 2.1
# Compute graph Gr with the existing values of r.
gr = retime(g, r)
# STEP 2.2
# Run Algorithm CP on the graph Gr to determine delta(v) for each vertex v.
_, delta = cp(gr, return_delta=True)
# STEP 2.3
# For each v such that delta(v) > c, set r(v) <- r(v) + 1
for v in delta.keys():
if delta[v] > c:
r[v] += 1
# STEP 3
# Run Algorithm CP on the circuit Gr. If we have that cp(gr) > c, then no feasible retiming exists.
# Otherwise, r is the desired retiming.
clock = cp(gr)
if clock > c:
return None
return r
def opt2(g, show_wd=False):
"""
Given a synchronous circuit :math:`G`, this algorithm determines a retiming :math:`r` such that the clock period of
:math:`G_r` is as smallas possible.
+------------------+----------------------+
| Time complexity | :math:`O(VE \log V)` |
+------------------+----------------------+
| Space complexity | :math:`O(V^2)` |
+------------------+----------------------+
:param g: A NetworkX (Multi)DiGraph representing a synchronous circuit.
:param show_wd: Print matrices W and D.
:return: The retimed graph having the smallest possible clock period.
"""
# STEP 1
# Compute W and D using Algorithm WD.
W, D = wd(g, show=show_wd)
# STEP 2
# Sort the elements in the range of D.
D_range = np.unique(list(D.values()))
D_range.sort()
# STEP 3
# Binary search among the elements D(u, v) for the minimum achievable clock period. To test whether each potential
# clock period c is feasible, apply Algorithm FEAS.
clock, r = __binary_search(D_range, feas, g)
# STEP 4
# For the minimum achievable clock period found in Step 3, use the values for the r(v) found by Algorithm FEAS
# as the optimal retiming.
return retime(g, r)
|
# -*- coding: utf-8 -*-
'''
Given an array nums and a value val, remove all instances of
that value in-place and return the new length.
Do not allocate extra space for another array, you must do this
by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter what
you leave beyond the new length.
Example:
Given nums = [3,2,2,3], val = 3.
Your function should return length = 2, with the first two elements of
nums being 2. It doesn't matter what you leave beyond the returned length.
'''
class Solution(object):
def remove_element(self, nums, val):
idx = 0
for i in range(len(nums)):
if nums[i] != val:
nums[idx] = nums[i]
idx += 1
return idx
if __name__ == '__main__':
nums = [3, 2, 2, 3]
val = 3
s = Solution()
n = s.remove_element(nums, val)
print(n)
print(nums)
|
# -*- coding: utf-8 -*-
class Solution(object):
def is_valid_sudoku(self, board):
n = 9
used_column = [[False] * n for i in range(n)]
used_row = [[False] * n for i in range(n)]
used_block = [[False] * n for i in range(n)]
for i in range(n):
for j in range(n):
if board[i][j] == '.':
continue
num, block = int(board[i][j]) - 1, i // 3 * 3 + j // 3
if used_column[i][num] or used_row[j][num] or used_block[block][num]:
return False
used_column[i][num] = used_row[j][num] = used_block[block][num] = True
return True
if __name__ == '__main__':
s = Solution()
board = [
['5', '3', '.', '.', '7', '.', '.', '.', '.'],
['6', '.', '.', '1', '9', '5', '.', '.', '.'],
['.', '9', '8', '.', '.', '.', '.', '6', '.'],
['8', '.', '.', '.', '6', '.', '.', '.', '3'],
['4', '.', '.', '8', '.', '3', '.', '.', '1'],
['7', '.', '.', '.', '2', '.', '.', '.', '6'],
['.', '6', '.', '.', '.', '.', '2', '8', '.'],
['.', '.', '.', '4', '1', '9', '.', '.', '5'],
['.', '.', '.', '.', '8', '.', '.', '7', '9']
]
print(s.is_valid_sudoku(board))
|
# -*- coding: utf-8 -*-
class Solution(object):
def generate_parenthesis(self, n):
res = []
self.generate(n, n, '', res)
return res
def generate(self, left_num, right_num, s, res):
if left_num == 0 and right_num == 0:
res.append(s)
if left_num > 0:
self.generate(left_num - 1, right_num, s + '(', res)
if right_num > 0 and right_num > left_num:
self.generate(left_num, right_num - 1, s + ')', res)
if __name__ == '__main__':
s = Solution()
print(s.generate_parenthesis(3))
|
# -*- coding: utf-8 -*-
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def add_two_numbers(self, l1, l2):
extra = 0
head = ListNode(0)
p = head
while l1 or l2 or extra:
sum = (l1.val if l1 else 0) + (l2.val if l2 else 0) + extra
p.next = ListNode(sum % 10);
p = p.next
extra = sum // 10
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return head.next
if __name__ == '__main__':
l1 = ListNode(2)
l1.next = ListNode(4)
l1.next.next = ListNode(3)
l2 = ListNode(5)
l2.next = ListNode(6)
l2.next.next = ListNode(4)
s = Solution()
head = s.add_two_numbers(l1, l2)
while head:
print(head.val,)
head = head.next
|
class Person:
def __init__(self, name, fist_name, second_name):
self.name = name
self._fist_lastname = fist_name
self.__second_lastname = second_name
def publicMethod(self):
self.__privateMethod()
def __privateMethod(self):
print(self.name)
print(self._fist_lastname)
print(self.__second_lastname)
def get_second_lastname(self):
return self.__second_lastname
def set_second_lastname(self, second_lastname):
self.__second_lastname = second_lastname
p1 = Person("Dan", "Kop", "Kap")
p1.publicMethod()
print(p1.name)
print(p1._fist_lastname)
print(p1.get_second_lastname())
|
class MyClass:
class_var = "class Variable"
def __init__(self):
self.instance_var = "Instance Var"
@staticmethod
def static_method():
print("Estatic Method!")
print(MyClass.class_var)
# Desde un metodo estatico no se puede acceder a una variable de instancia
@classmethod
def class_method(cls):
print("Class method" + str(cls))
print(cls.class_var)
# Desde un contexto estatico (metodo de clase) no se puede acceder a una variable de instancia
def instance_method(self):
self.static_method()
self.class_method()
print(self.instance_var)
print(self.class_var)
MyClass.static_method()
MyClass.class_method()
print("\n diferent******")
obj1 = MyClass()
obj1.instance_method()
|
print("Provides the following book's data: ")
name = input("Provides the name:")
id = int(input("Provides the ID:"))
price = float(input("Provides the price: "))
freeShipping = input("Indicates whether shipping is free(Yeah/Nop): ")
if freeShipping == "Yeah":
freeShipping = True
elif freeShipping == "Nop":
freeShipping = False
else:
freeShipping = "Incorrect value, it must be True or False"
print("Name:", name)
print("ID:", id)
print("price:", price)
print("free shipping?", freeShipping)
|
from cuadrado import Square
from rectangulo import Rectangle
square = Square(2, "Black")
rectangle = Rectangle(4, 5, "Green")
print("Square", square)
print("Area square", square.area())
print("Rectangle", rectangle)
print("Area rectangle", rectangle.area())
#metodo para saber el orden de los metodos
print(Square.mro())
|
# Uses python3
import sys
def get_fibo(n):
if n <= 1:
return n
previous = 0
current = 1
for _ in range(n - 1):
previous, current = current, previous + current
return current
def get_fibonacci_huge_eff(n, m):
cycle = [0, 1]
if n < m:
return get_fibo(n)
i = 2
while True:
cycle.append(get_fibo(i) % m)
if (cycle[i - 1], cycle[i]) == (0, 1):
break
i += 1
cycle_len = len(cycle)
return cycle[n % cycle_len]
if __name__ == '__main__':
input = sys.stdin.read();
n, m = map(int, input.split())
print(get_fibonacci_huge_eff(n, m))
|
def main():
size = 6
names = ["Sally", "Tom","Sameer", "Rishika", "Fernando", "Camilio"]
searchValue = ""
index = 0
found = False
keepGoing = "y"
while keepGoing == "y":
print("Do you want to search the array?")
keepGoing = input("(Enter y for yes.)").lower()
if keepGoing == "y":
index,found = searchFunction(index,searchValue,found,names,size)
outputMod(index,found)
else:
print(" Thanks for searching")
def searchFunction(index,searchValue,found,names,size):
searchValue = input("Enter a name to search for in the array: ").lower()
while found == False and index <= size-1:
if names[index].lower() == searchValue:
found = True
else:
index = index + 1
return index,found
def outputMod(index,found):
if found:
print("That name was found at subscript ", index)
else:
print("That name was not found in the array.")
main()
|
#
# @lc app=leetcode.cn id=234 lang=python3
#
# [234] 回文链表
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# 直接输出看反转之后一样与否
# class Solution:
# def isPalindrome(self, head: ListNode) -> bool:
# p = head
# tmp_list = []
# while p:
# tmp_list.append(p.val)
# p = p.next
# if tmp_list == tmp_list[::-1]:
# return True
# else:
# return False
# 快慢指针+栈
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
slow = fast = head
stack = []
while fast and fast.next:
stack.append(slow)
fast = fast.next.next
slow = slow.next
if fast:
slow = slow.next
while stack:
tmp = stack.pop()
if tmp.val == slow.val:
slow = slow.next
else:
return False
return True
# @lc code=end
|
def read(command):
"""Gets the input value from the user"""
userInput = None
while userInput is None:
try:
userInput = input(command)
except IOError :
print("There was an error reading the value")
continue
except :
print("\nSomething happened. Exiting...")
exit()
return userInput
|
# ----------------------------------------------------------------------
# EXAMPLE: Fermi-Dirac function in Python.
#
# This simple example shows how to use Rappture within a simulator
# written in Python.
# ======================================================================
# AUTHOR: Michael McLennan, Purdue University
# Copyright (c) 2004-2012 HUBzero Foundation, LLC
#
# See the file "license.terms" for information on usage and
# redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
# ======================================================================
import Rappture
import sys
from math import *
# open the XML file containing the run parameters
driver = Rappture.library(sys.argv[1])
Tstr = driver.get('input.(temperature).current')
T = Rappture.Units.convert(Tstr, to="K", units="off")
Efstr = driver.get('input.(Ef).current')
Ef = Rappture.Units.convert(Efstr, to="eV", units="off")
print Tstr, T, Efstr, Ef
kT = 8.61734e-5 * T
Emin = Ef - 10*kT
Emax = Ef + 10*kT
E = Emin
dE = 0.005*(Emax-Emin)
# Label the output graph with a title, x-axis label,
# y-axis label, and y-axis units
driver.put('output.curve(f12).about.label','Fermi-Dirac Factor',append=0)
driver.put('output.curve(f12).xaxis.label','Fermi-Dirac Factor',append=0)
driver.put('output.curve(f12).yaxis.label','Energy',append=0)
driver.put('output.curve(f12).yaxis.units','eV',append=0)
while E < Emax:
f = 1.0/(1.0 + exp((E - Ef)/kT))
line = "%g %g\n" % (f, E)
Rappture.Utils.progress(((E-Emin)/(Emax-Emin)*100),"Iterating")
driver.put('output.curve(f12).component.xy', line, append=1)
E = E + dE
Rappture.result(driver)
sys.exit()
|
# 复合数据类型---集合等
# 1.元组
tup1 = ('a', 2)
print(tup1[0])
# tup1[1]=1 #TypeError: 'tuple' object does not support item assignment
# 2.集合
country = {'china', 'USA', 'Russia', 'France'}
print(country)
if ('Germany' in country):
print('Germany 在 country集合里')
else:
print('Germany 不在country集合里')
setA = set('abcdbdcfc')
setB = set('docker')
print(setA - setB) # 差集
print(setA | setB) # 并集
print(setA & setB) # 交集
print(setA ^ setB) # 不同时存在的集
dict = {}
dict[1] = 'one'
dict[2] = 'two'
print('dict=', dict)
# dict 键值对 相当于map
myDict = {'name': 'gaojc', 'id': 8171, 'height': '170cm'}
print('myDict.keys()=', myDict.keys())
print('myDict.values()=', myDict.values())
print('myDict=', myDict)
print('myDict.get(\'id\')=', myDict.get('id'))
# x 这个key不存在,返回 自定义的newStr
print("myDict.get('x','newStr')=", myDict.get('x', 'newStr'))
# 删除一个key 用pop(key)
myDict.pop('height')
print('myDict=', myDict)
# set 存储key的集合,没有value,key不能重复
# class set([iterable])
mySet = set([1, 2, 3])
print('mySet=', mySet)
mySet = set(range(10))
print('mySet 2=', mySet)
mySet = set({'w', 3, 'd'})
print('mySet 3=', mySet)
# issubset(other) Test whether every element in the set is in other.
print('issubset=', set([3]).issubset(mySet))
# use add(key) method to add element to set
mySet.add('z')
print('mySet4=', mySet)
mySet.remove('d') # remove(key) 删除一个元素
print('mySet5=', mySet)
print(type(mySet))
# 2.list 列表
nums = [1, 2, 'a', ['doc', [9, 8, ]], ] # 4个元素,逗号可以放最后
print('a list named nums=', nums)
print('nums[3][1][1]=', nums[3][1][1])
print('nums[-0]=', nums[-0])
print('nums[-2]=', nums[-2]) # 倒数下标往前
nums[1] = nums[2]
print('nums=', nums)
nums = nums + [3] # 追加一个元素到list后
print(nums)
print(nums[3] * 2) # 重复打印2次
print('a' in nums) # 判断元素是否在列表 用 in
print("ch" in 'china')
print('U' not in 'CPU') # not in
print(not 1 in nums)
print(not 2 in nums[3][1])
# len()函数获取列表长度
print('nums\'s lenth=', len(nums))
# insert()指定插入位置
nums.insert(2, "book")
print(nums)
# index() 返回元素首次出现的下标 ,类似于java的indexOf()
print(nums.index("a"))
print(nums.count('a')) # 返回a 在nums里的出现次数
print(nums.remove('a')) # 移除列表中找到的第一次的此元素
print(nums)
# 数组顺序反转
nums.reverse()
print(nums)
# 移除列表的最后一个元素,返回该元素
print("nums.pop()=", nums.pop())
word = ['chin']
word.append('ese') # 在列表尾部追加用append
print(word)
word = word[0] + word[1]
print(word)
# range(n) range函数创建从0-n的有序序列
rang = list(range(5))
print(rang)
# range(x,y) range函数创建从x到y-1的有序序列
rang = list(range(2, 6))
print(rang)
|
import math
def paginacijaRezultata(rezultati, kljucevi): #prosledjuje se recnik(rezultati) i lista kljuceva istog recnika(kljucevi)
brPoStr = 5
broj_stranica = math.ceil(len(rezultati.keys()) / brPoStr)
#inicijalno se pokazuje prva strana pretrazenih rezultata
i = 0
for rez in rezultati.keys():
print(str(i + 1) + ". " + str(rez) + ' -> ' + str(rezultati.get(rez)))
i = i + 1
if i == brPoStr:
break
print('Strana 1 od', broj_stranica, '\n')
#meni za prikaz paginacije rezultata
odabir = True
trenutnaStrana = 1 #trenutna strana prikaza pri ulasku u while petjlu je 1
while odabir:
print("IZABERITE OPCIJU:")
print("0. Izlazak iz paginacionog prikaza rezultata.")
print("1. Prethodna stranica.")
print("2. Sledeća stranica.")
print("3. Odabir broja rezultata pretrage na jednoj strani.")
opcija = input("Vaša opcija: ")
if opcija.isnumeric() == True:
answer = int(opcija)
if answer == 1:
if trenutnaStrana - 1 <= 0: #provera - ne moze se ici u nazad ako smo na prvoj stranici
print("\nVAN OPSEGA! Možete izabrati samo sledeću stranicu.\n")
else:
trenutnaStrana = trenutnaStrana - 1 #svaki put kada se izabere opcija "Prethodna stranica" trenutnaStrana se smanji za 1
i = brPoStr * (trenutnaStrana - 1) #i pretstravlja pocetak iteracije
kraj = brPoStr * trenutnaStrana #kraj iteracije
print("\nREZULTATI PRETRAGE:")
for rez in range(i, kraj):
print(str(i + 1) + ". " + str(kljucevi[rez]) + " -> " + str(rezultati.get(kljucevi[rez]))) #stampa se kljuc recnika(html stranica) i uparena vrednost
i = i + 1
if i == i + brPoStr:
break
print('Strana', trenutnaStrana, 'od', broj_stranica, '\n') #numeracija stranica
elif answer == 2:
if trenutnaStrana + 1 > broj_stranica: #provera - ne moze se ici u napred ako smo na poslednjoj stranici
print("\nVAN OPSEGA! Možete izabrati samo prethodnu stranicu.\n")
else:
trenutnaStrana = trenutnaStrana + 1
i = brPoStr * (trenutnaStrana - 1)
#kod ispisa poslednje strane prikaza rezultata moze se desiti da ostanje manji broj rezultata nego
#na prethodnim stranama prikaza rezultata zbog toga je potrebno pomeriti kraj iteriranja u nazad
if trenutnaStrana == broj_stranica:
kraj = brPoStr * (trenutnaStrana - 1) + (len(rezultati) - brPoStr * (trenutnaStrana - 1))
#ako je broj prikaza rezultata na poslednjoj strani isti kao i kod prethodnih
else:
kraj = brPoStr * trenutnaStrana
print("\nREZULTATI PRETRAGE:")
for rez in range(i, kraj):
print(str(i + 1) + ". " + str(kljucevi[rez]) + " -> " + str(rezultati.get(kljucevi[rez])))
i = i + 1
if i == i + brPoStr:
break
print('Strana', trenutnaStrana, 'od', broj_stranica, '\n')
elif answer == 3:
uredu = True
while uredu:
broj = input("Izaberite broj rezultata pretrage na jednoj strani: ")
if broj.isnumeric() == True:
brPoStr = int(broj)
if brPoStr > 0:
# print('Broj rezultata pretrage po stranici:', brPoStr)
# print("")
break
else:
print("\nGREŠKA! Morate uneti broj veći od nule.\n")
else:
print("\nGREŠKA! Morate uneti isključivo broj.\n")
broj_stranica = math.ceil(len(rezultati.keys()) / brPoStr)
print("\nREZULTATI PRETRAGE:")
i = 0
for rez in rezultati.keys():
print(str(i + 1) + ". " + str(rez) + ' -> ' + str(rezultati.get(rez)))
i = i + 1
if i == brPoStr:
break
print('Strana 1 od', broj_stranica, '\n')
trenutnaStrana = 1
elif answer == 0:
print("\nIZAŠLI STE IZ PAGINACIONOG PRIKAZA REZULTATA.\n")
return
else:
print("\nGREŠKA! Morate izabrati jednu od ponuđenih opcija.\n")
else:
print("\nGREŠKA! Morate izabrati jednu od ponuđenih opcija.\n")
|
from graph import Graph
class GraphSearch(Graph):
def __init__(self):
super().__init__()
# 3(d) (3 points) (You must submit code for this question!) In a class called GraphSearch, implement ArrayList<Node> DFTRec(final Node start, final Node end), which recursively returns an ArrayList of the Nodes in the Graph in a valid Depth-First Search order. The first node in the array should be start and the last should be end. If no valid DFS path goes from start to end, return null.
def DFTRec(self, start_node=0):
def __DFSHelper(dft_arr, curr_node):
curr_node.visited = True
dft_arr.append(curr_node)
for neighbor in curr_node.connections:
if neighbor and not neighbor[0].visited:
dft_arr = __DFSHelper(dft_arr, neighbor[0])
return dft_arr
start_node = self.getNode(start_node)
dfs = __DFSHelper([], start_node)
self.resetNodes() # Resets the nodes for graph to be searched again
if len(dfs) == len(self.nodes): # If all nodes have been visited:
return dfs
else:
return None
# Performs a depth-first search for the end node, and returns the path to it if found.
def DFSRec(self, start_node=0, end_node=1):
def __DFSHelper(dfs_arr, curr_node, found=False):
curr_node.visited = True
dfs_arr.append(curr_node)
if curr_node.val == str(end_node): # Checks if the string value of the node is equal to the stringified end_node.
found = True
else:
for neighbor in curr_node.connections:
if neighbor and not found and not neighbor[0].visited:
dfs_arr, found = __DFSHelper(dfs_arr, neighbor[0], found)
return dfs_arr, found
start_node = self.getNode(start_node)
dfs, found = __DFSHelper([], start_node)
self.resetNodes() # Resets the nodes for graph to be searched again
if found:
return dfs
else:
return None
# 3(e) (5 points) (You must submit code for this question!) In your GraphSearch class, implement ArrayList<Node> DFTIter(final Node start, final Node end), which iteratively returns an ArrayList of the Nodes in the Graph in a valid Depth-First Search order. The first node in the array should be start and the last should be end. If no valid DFS path goes from start to end, return null.
def DFTIter(self, start_node):
stack, visited = [], []
curr_node = self.getNode(start_node) # Ensures that start_node is a Node object.
curr_node.visited = True # Mark current node visited.
stack.append(curr_node) # Stacks the node.
while len(stack) > 0: # While there are nodes in the stack
curr_node = stack.pop() # Pops the top node and makes it the current one.
visited.append(curr_node) # Add it to the visited list.
curr_node.visited = True # Marks the node visited
for neighbor in curr_node.connections: # Loops through the neighbors:
if not neighbor[0].visited:
stack.append(neighbor[0]) # Stacks the unvisited neighbors.
self.resetNodes() # Resets the nodes for graph to be searched again
if len(visited) == len(self.nodes): # If all nodes have been visited:
return visited
else:
return None
# Performs a depth-first search for end_node iterativly, and returns the path if found:
def DFSIter(self, start_node, end_node):
stack, visited = [], []
curr_node = self.getNode(start_node) # Ensures that start_node is a Node object.
curr_node.visited = True # Mark current node visited.
stack.append(curr_node) # Stacks the node.
while len(stack) > 0: # While there are nodes in the stack
curr_node = stack.pop() # Pops the top node and makes it the current one.
visited.append(curr_node) # Add it to the visited list.
curr_node.visited = True # Marks the node visited
if curr_node.val == str(end_node):
self.resetNodes() # Resets the nodes for graph to be searched again:
return visited
else:
for neighbor in curr_node.connections: # Loops through the neighbors:
if not neighbor[0].visited:
stack.append(neighbor[0]) # Stacks the unvisited neighbors.
self.resetNodes() # Resets the nodes for graph to be searched again
return None # If node was not found, returns None
# 3(f) (3 points) (You must submit code for this question!) In your GraphSearch class, implement ArrayList<Node> BFTRec(final Graph graph), which recursively returns an ArrayList of the Nodes in the Graph in a valid Breadth-First Traversal order.
def BFTRec(self, start_node=0):
def __BFTHelper(visited, curr_node, found=False):
curr_node.visited = True
visited.append(curr_node)
for neighbor in curr_node.connections:
if neighbor and not found and not neighbor[0].visited:
visited = __BFTHelper(visited, neighbor[0], found)
return visited
start_node = self.getNode(start_node)
bft = __BFTHelper([], start_node)
self.resetNodes() # Resets the nodes for graph to be searched again
if len(bft) == len(self.nodes): # If all nodes have been visited:
return bft
else:
return None
# Performs a breadth-first-search for a node Recursivly, and returns the path to it if found:
def BFSRec(self, start_node=0, end_node=1):
def __BFTHelper(visited, curr_node, found=False):
curr_node.visited = True
visited.append(curr_node)
if curr_node.val == end_node:
return visited, True
else:
for neighbor in curr_node.connections:
if neighbor and not found and not neighbor[0].visited:
visited, found = __BFTHelper(visited, neighbor[0], found)
return visited, found
start_node, end_node = self.getNode(start_node), str(end_node)
bft, found = __BFTHelper([], start_node)
self.resetNodes() # Resets the nodes for graph to be searched again
if found:
return bft
else:
return None
# 3(g) (5 points) (You must submit code for this question!) In your GraphSearch class, implement ArrayList<Node> BFTIter(final Graph graph), which iteratively returns an ArrayList of all of the Nodes in the Graph in a valid Breadth-First Traversal.
def BFTIter(self, start_node):
queue, visited = [], []
curr_node = self.getNode(start_node)
curr_node.visited = True # Mark visited
queue.append(curr_node)
# While there are nodes in the queue:
while len(queue) > 0:
curr_node = queue.pop(0) # Gets the first node in the queue
curr_node.visited = True # Marks the node as visited
visited.append(curr_node) # Adds it to the visited list
for connection in curr_node.connections:
neighbor = connection[0]
if not neighbor.visited:
queue.append(neighbor)
self.resetNodes() # Resets the nodes for graph to be searched again
if len(visited) == len(self.nodes): # If all nodes have been visited:
return visited
else:
return None
# Performs a breadth-first search for end_node iteratively, and returns the path if found:
def BFSIter(self, start_node, end_node):
queue, visited = [], []
curr_node = self.getNode(start_node)
end_node = str(end_node)
curr_node.visited = True # Mark visited
queue.append(curr_node)
# While there are nodes in the queue:
while len(queue) > 0:
curr_node = queue.pop(0) # Gets the first node in the queue
curr_node.visited = True # Marks the node as visited
visited.append(curr_node) # Adds it to the visited list
if curr_node.val == end_node:
self.resetNodes() # Resets the nodes for graph to be searched again
return visited
else:
for connection in curr_node.connections:
neighbor = connection[0]
if not neighbor.visited:
queue.append(neighbor)
self.resetNodes() # Resets the nodes for graph to be searched again
return None # If node was not found, returns None
def printYellow(txt): print("\033[93m {}\033[00m" .format(txt))
def printResult(self, result):
if result:
for i in range (len(result)-1):
print(result[i].val, end='->')
GraphSearch.printYellow(result[len(result)-1].val)
else:
print("\nNo path found")
if __name__ == "__main__":
print("Creating Graph...")
graph = GraphSearch()
for i in range(10):
graph.addNode(i)
for i in range(1, 9):
graph.addUndirectedEdge(i, i+1)
print(graph)()
print("Adding Edge...")
graph.addUndirectedEdge("0", "1")
graph.addUndirectedEdge("1", "2")
print("Doing Searches...")
graph.printResult(graph.DFSRec(0, 2))
graph.printResult(graph.DFSIter(0, 2))
graph.printResult(graph.BFSRec(0, 2))
graph.printResult(graph.BFSIter(0, 2))
print("Doing Traversals...")
graph.printResult(graph.DFTRec(0))
graph.printResult(graph.DFTIter(0))
graph.printResult(graph.BFTRec(0))
graph.printResult(graph.BFTIter(0))
|
#Challenge 2 Write a version of the Guess My Number game using a GUI
from tkinter import *
import random
class Application(Frame):
def __init__ (self,master):
super(Application,self).__init__(master)
self.grid()
self.create_widgets()
self.random_number = random.randint(1,5)
def create_widgets(self):
Label(self,
text="Enter a number to guess between 1-20").grid(row=0, column=0, sticky=W)
self.number = Entry(self)
self.number.grid(row=1, column=0, sticky=W)
Button(self,
text="Guess",
command= self.guess_number).grid(row=2, column=0, sticky=W)
self.message = Text(self, width=20, height=5, wrap = WORD)
self.message.grid(row=3, column=0, sticky=W)
def guess_number(self):
number = int(self.number.get())
if number == self.random_number:
self.message.delete(0.0, END)
self.message.insert(0.0, "That is the correct number!")
else:
self.message.delete(0.0, END)
self.message.insert(0.0, "Incorrect! Guess Again")
root = Tk()
root.title("Guess The Number")
app = Application(root)
root.mainloop()
|
# Write a Who's Your Daddy? program that lets the user enter the name of a male
# and produces the name of his father. Allow the user to add, replace, and
# delete son-father pairs.
father_son = {
"John Lennon": "Julian Lennon",
"Ken Griffey Sr.": "Ken Griffey Jr.",
"Bruce Matthews": "Clay Matthews",
"Jerry Stiller": "Ben Stiller",
"Martin Sheen": "Charlie Sheen",
}
print("""
\t Who Is Your Daddy? Program
\t 1. Add a Father/Son Pair
\t 2. Replace a Father/Son Pair
\t 3. Delete a Father/Son Pair
\t 4. Show all Father/Son Pairs
\t 5. Quit
""")
while True:
choice = input("Enter a number: ")
if choice == "1":
add_father = input("Enter a father name: ")
if add_father not in father_son:
add_son = input("Add the son's name: ")
father_son[add_father] = add_son
print(add_father,"and",add_son,"have been added.")
else:
print("Name already in database.")
elif choice == "2":
replace_father = input("Who's son do you want to replace? ")
if replace_father in father_son:
new_son = input("Who is the new son?")
father_son[replace_father] = new_son
print(new_son,"is the new son of",replace_father)
else:
print("Name not found in database.")
elif choice == "3":
delete_father = input("Who do you want to remove? ")
if delete_father in father_son:
del father_son[delete_father]
print(delete_father,"has been deleted.")
else:
print("Name not found.")
elif choice == "4":
for key, value in father_son.items():
print(key,value)
elif choice == "5":
break
input("Press Enter to exit.")
|
#Challenge 2 Create a War card game
import cards, games
class War_Card(cards.Card):
def __init__(self, rank, suit):
super(War_Card,self).__init__(rank,suit)
@property
def value_hand(self):
v = War_Card.RANKS.index(self.rank) + 1
if v == 1:
v == 14
else:
None
return v
class War_Deck(cards.Deck):
def populate(self):
for rank in War_Card.RANKS:
for suit in War_Card.SUITS:
self.cards.append(War_Card(rank,suit))
class War_Hand(cards.Hand):
def __init__(self,name):
super(War_Hand,self).__init__()
self.name = name
def __str__(self):
if self.cards:
rep = ""
for card in self.cards:
rep += str(card) + "\t"
else:
rep = "<empty>"
return rep
def draw(self):
top_card = self.cards[0]
self.cards.remove(top_card)
return top_card
@property
def value_hand(self):
for card in self.cards:
val = card.value
return val
class War_Game(object):
def __init__(self):
self.name = input("Enter Your Name: ")
self.player = War_Hand(self.name)
self.computer = War_Hand("Computer")
self.deck = War_Deck()
self.deck.populate()
self.deck.shuffle()
def play(self):
hands = [self.player,self.computer]
self.deck.deal(hands,per_hand=26)
while True:
input("Press Enter to draw a card")
your_card = self.player.draw()
cpu_card = self.computer.draw()
print(self.player.name,your_card)
print(self.computer.name,cpu_card)
if your_card.value_hand() > cpu_card.value_hand():
print("You win!")
elif your_card.value_hand() < cpu_card.value_hand():
print("You lose!")
else:
print("It's a tie!")
if len(self.computer.cards) == 0 and len(self.player.cards) == 0:
print("Players out of cards.")
break
game = War_Game()
game.play()
|
# Write a CharacterCreate Program for a role-playing game.
# The player should be given a pool of 30 points to spend on four attributes:
# Strength, Health, Wisdom, and Dexterity
# The player should be able to spend points from the pool on any attribute
# and should also be able to take points from an attribute and put them back
# in the pool.
attributes = {
"1. strength": 0,
"2. wisdom": 0,
"3. dexterity": 0,
"4. health": 0,
"5. quit": "Press 5 to exit this menu."
}
points = 30
while True:
for key, value in attributes.items():
print(key,value)
print("You have",points,"points available.")
stat = input("\nChoose an option: ")
if points == 0:
print("No points left to spend")
continue
if stat == "1":
add_subtract_str = input("Press 1 to Add points. Press 2 to Subtract points")
if add_subtract_str == "1":
add_str = int(input("Enter a number to add: "))
points -= add_str
attributes["1. strength"] += add_str
print("Strength: ",attributes["1. strength"],"Points left:",points)
if add_subtract_str == "2":
sub_str = int(input("Enter a number to subtract: "))
if attributes["1. strength"] == 0:
print("No points to subtract")
else:
points += add_str
attributes["1. strength"] -= add_str
print("Strength: ",attributes["1. strength"],"Points left:",points)
if stat == "2":
add_subtract_wis = input("Press 1 to Add points. Press 2 to Subtract points")
if add_subtract_wis == "1":
add_wis = int(input("Enter a number to add: "))
points -= add_wis
attributes["2. wisdom"] += add_wis
print("Wisdom: ",attributes["2. wisdom"],"Points left:",points)
if add_subtract_wis == "2":
sub_wis = int(input("Enter a number to subtract: "))
if attributes["2. wisdom"] == 0:
print("No points to subtract")
else:
points += add_wis
attributes["2. wisdom"] -= add_wis
print("Wisdom: ",attributes["2. wisdom"],"Points left:",points)
if stat == "3":
add_subtract_dex = input("Press 1 to Add points. Press 2 to Subtract points")
if add_subtract_dex == "1":
add_dex = int(input("Enter a number to add: "))
points -= add_dex
attributes["3. dexterity"] += add_dex
print("Dexterity: ",attributes["3. dexterity"],"Points left:",points)
if add_subtract_dex == "2":
sub_dex = int(input("Enter a number to subtract: "))
if attributes["3. dexterity"] == 0:
print("No points to subtract")
else:
points += add_dex
attributes["3. dexterity"] -= add_dex
print("Dexterity: ",attributes["3. dexterity"],"Points left:",points)
if stat == "4":
add_subtract_hel = input("Press 1 to Add points. Press 2 to Subtract points")
if add_subtract_hel == "1":
add_hel = int(input("Enter a number to add: "))
points -= add_hel
attributes["4. health"] += add_hel
print("Health: ",attributes["4. health"],"Points left:",points)
if add_subtract_hel == "2":
sub_hel = int(input("Enter a number to subtract: "))
if attributes["4. health"] == 0:
print("No points to subtract")
else:
points += add_hel
attributes["4. health"] -= add_hel
print("Health: ",attributes["4. health"],"Points left:",points)
if stat == "5":
break
|
#mahasiswa = ["Rayhan",2,"Teknik Informatika"]
#print(mahasiswa[0:2])
#nama = "rayhan whoo ouuu aaa eee"
#game = "Mobile Legend"
#print(game[8:11])
#angka = 6
#if angka == 5:
# print("Uhuy")
#else:
# print("Edan")
#hero = "layla"
#if hero is "Zilong":
# print(hero, "fighter Bos")
#elif hero is "layla":
# print(hero, "Marksman Bos")
#else:
# print("Hero nya Leungit")
#angka = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#hari = ["Senin", "Selasa", "Rabu", "kamis", "jum'at", "Sabtu", "Minggu"]
#for i in hari:
# print(i)
#for i in range(0, 10, 2):
# if i is 4:
# print ("Dah Lah")
# break
# print(i)
#for i in range(0, 10, 2):
# if i is 4:
# print ("Dah Lah")
# continue
# print(i)
#angka = 0
#while angka < 5:
# print(angka)
# angka+=1
user = "udin"
passw = "123"
username = input("Masukan Username : ")
password = input("Masukan Password : ")
while username != user or password != passw:
if username and password == user and passw:
print("Kamu Masuk")
else:
print("salah")
username = input("Masukan Username : ")
password = input("Masukan Password : ")
|
def purge(operators, sequence):
seq = ''
for i, value in enumerate(zip([''] + operators, sequence)):
o, d = value
seq += o
if i != len(sequence) - 1 and d == '0' and o in '+-':
continue
seq += d
return seq
def generate(sequence):
l = len(sequence) - 1
sequence = [c for c in sequence]
operators = ['' for i in xrange(l)]
yield purge(operators, sequence)
for n in xrange(3**(l) - 1):
i = l - 1
while True:
if operators[i] == '-':
operators[i] = ''
i -= 1
continue
elif operators[i] == '+':
operators[i] = '-'
else:
operators[i] = '+'
break
yield purge(operators, sequence)
for case in xrange(input()):
expressions = 0
for sequence in generate(raw_input()):
if not sequence:
expressions += 1
continue
#n = eval(sequence)
#if not n%2 or not n%3 or not n%5 or not n%7:
# expressions += 1
print 'Case #%d: %d' % (case + 1, expressions)
|
import math
############### Account Info Summary #####################
Account_List = ['0915' , '0896' , '7001' , '5076' , '9587' , '0562' , '9967' , '0584'] # Account members' numbers
BasicData = 15
BasicDataFee = 90
ExtraDataFee = input("What's the extra data usage fee(unit: $)?")
DataShare = range(len(Account_List))
BasicFee = range(len(Account_List))
for i in range(len(Account_List)): # Enter the share info for each number
print("--------------------------------")
print("Current Account: ")
print(Account_List[i])
DataShare[i] = input("Data Share Percentage(unit: %)?")
DataShare[i] = float(DataShare[i])
BasicFee[i] = input("Basic payment(unit: $)?")
BasicFee[i] = float(BasicFee[i])
############### Payment Calculation #####################
PaymentList = range(len(Account_List))
ExtraDataShare = range(len(Account_List))
for j in range(len(Account_List)):
if DataShare[j] > (1/len(Account_List)):
ExtraDataShare[j] = DataShare[j]
else:
ExtraDataShare[j] = 0
ExtraDataShareSum = 0
for j in range(len(Account_List)):
ExtraDataShareSum = ExtraDataShareSum + ExtraDataShare[j]
if ExtraDataShareSum != 0:
for j in range(len(Account_List)):
PaymentList[j] = BasicFee[j] + (BasicDataFee / len(Account_List)) + (int(ExtraDataFee) * (ExtraDataShare[j] / ExtraDataShareSum))
else:
for j in range(len(Account_List)):
PaymentList[j] = BasicFee[j] + (BasicDataFee / len(Account_List))
############### Print Payment #####################
print("---------------------------------------------")
print("Print Payment")
for k in range(len(Account_List)):
print("***")
print('Payment ($) for', Account_List[k])
print(PaymentList[k])
|
def factorial(n):
if n > 1:
return n * factorial(n - 1)
else:
return 1
print('1!={:,}, 3!={:,}, 5!={:,}, 10!={:,}'.format(
factorial(1),
factorial(3),
factorial(5),
factorial(10),
))
def fibonacci_co():
current = 0
next = 1
while True:
current, next = next, next + current
yield current
for n in fibonacci_co():
if n > 100:
break
print(n, end=', ')
|
import os
import csv
import statistics
from transaction import Transaction
def main():
print_header()
filename = get_data_file()
transactions = load_file(filename)
query_data(transactions)
def print_header():
print('Real Estate Data Mining')
def get_data_file():
base_folder = os.path.dirname(__file__)
file_path = os.path.join(base_folder, 'data', 'transactions.csv')
return file_path
def load_file(filename):
print('Loading data from: {}'.format(filename))
transactions = []
with open(filename, 'r', encoding='utf-8') as fin:
reader = csv.DictReader(fin)
for row in reader:
transaction = Transaction.create_from_dict(row)
transactions.append(transaction)
return transactions
def query_data(data):
data.sort(key=lambda transaction: transaction.price)
high_transaction = data[-1]
print('Most expensive house: ${:,}'.format(high_transaction.price))
low_transaction = data[0]
print('Least expensive house: ${:,}'.format(low_transaction.price))
prices = (
transaction.price
for transaction in data
)
average_price = statistics.mean(prices)
print('Average house price: ${:,}'.format(int(average_price)))
two_bed_prices = (
transaction.price
for transaction in data
if transaction.beds == 2
)
average_2bed_price = statistics.mean(two_bed_prices)
print('Average 2 bed house price: ${:,}'.format(int(average_2bed_price)))
if __name__ == '__main__':
main()
|
#CALCULADORA nro6
# Esta calculadora realiza el calculo de la Distancia
# Declaracion de la variable
velocidad,tiempo=0.0,0.0
# Calculadora
velocidad=30
tiempo=15
distancia=velocidad*tiempo
#mostrar datos
print("velocidad = ", velocidad)
print("tiempo = ", tiempo)
print("distancia = ", distancia)
|
#CALCULADORA nro 12
# Esta calculadora realiza el calculo de la Velocidad Angular
# Declaracion de la variable
angulo,tiempo,velocidad_angular=0.0,0.0,0.0
# Calculadora
angulo=45
tiempo=14
velocidad_angular=angulo/tiempo
#mostrar datos
print("angulo = ", angulo)
print("tiempo = ", tiempo)
print("velocidad_angular = ", velocidad_angular)
|
def rearrange_digits(input_list):
"""
Rearrange Array Elements so as to form two number such that their sum is maximum.
Args:
input_list(list): Input List
Returns:
(int),(int): Two maximum sums
"""
# By examing the examples, e.g., [1, 2, 3, 4, 5] to [531, 42], and [2, 4, 5, 6, 8, 9] to [964, 852],
#we come up with the following ideas:
# 1. Sort the list in ascending order, using MergeSort (time complexity is O(n * log(n)))
# Since now the new list is sorted, the problem actually converted into this:
#the index of left list is just the even index of the original list, but instead in a descending order.
#for example, [5,3,1] is 5(index = 4), 3(index = 2), 1(index = 0)
# So is the case with the right list (the odd index). for example, [4,2] is 4(index = 3), 2(index = 1)
# Thus, based on this observation, we do the following:
# 2. Create two lists, i.e., left and right, to hold the values.
# 2.1 Iterate through the list in a descending order, put each number into the left and right lists, respectively and successively. (time complexity is O(n))
# 2.2 Return the lists and convert them into concatenated strings, and then wrap them in a list
# First we started to sort the list
sorted_list = mergesort(input_list)
# Then we get our two numbers
return get_two_number(sorted_list)
#-----------------------------------------the following are adapted from course work------
def mergesort(input_list):
if len(input_list) <= 1:
return input_list
mid = len(input_list) // 2
left = input_list[:mid]
right = input_list[mid:]
left = mergesort(left)
right = mergesort(right)
return merge(left, right)
def merge(left, right):
merged = []
left_index = 0
right_index = 0
while left_index < len(left) and right_index < len(right):
if left[left_index] > right[right_index]:
merged.append(right[right_index])
right_index += 1
else:
merged.append(left[left_index])
left_index += 1
merged += (left[left_index:])
merged += (right[right_index:])
return merged
#-----------------------------------------the above are adapted from course work------
# Now we define a function to return the two required numbers:
def get_two_number(sorted_list):
last_index = len(sorted_list) - 1 # Get last index
left_number = ''
right_number = ''
while last_index >= 0: # Time complexity is O(n)
left_number += str(sorted_list[last_index])
if last_index > 0: # Avoid situation that the last_index = 0, and the right_number will return sorted_list[-1]
right_number += str(sorted_list[last_index - 1])
last_index -= 2 # move to the next second number, which ensures we get an index array of even or odd numbers (5,3,1..., or 6,4,2,0).
left_number = int(left_number)
right_number = int(right_number)
return [left_number, right_number]
# The overall time complexity is O(nlog(n)) + O(n) = O(nlog(n))
def test_function(test_case):
output = rearrange_digits(test_case[0])
solution = test_case[1]
if sum(output) == sum(solution):
print("Pass")
else:
print("Fail")
# Test cases:
test_function([[4, 6, 2, 5, 9, 8], [964, 852]])
# Pass
test_function([[1, 2, 3, 4, 5], [542, 31]])
# Pass
test_function([[6, 8, 9, 1, 2], [961, 82]])
# Pass
test_function([[0,0,0,0,0], [0, 0]])
# Pass
# Another testing case
import random
l = [i for i in range(0, 9)] # a list containing 0 - 9
random.shuffle(l)
rearrange_digits(l)
#"[86420, 7531]"
|
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
# define a function of polysum
def polysum (n,s):
# the variable is n and s
# n is the number of sides
# s is the length of each side
import math
#import math module, in order to apply the tan function and pi
area = 0.25*n*s**2/math.tan(math.pi/n)
# calculcation of area
perimeter = n*s
# calculation of length of the regular polygum
sum = area + perimeter**2
return round (sum, 4)
# apply the build-in round function to round the 4 decimal places.
|
# Author: GerogeLiu
import random
# Find divisors
def find_divisors(n):
"""
Return a list of all integers that can divide n
param: n, integer
return: divisors, list
"""
divisors = []
for i in range(2, n):
if n % i == 0:
divisors.append(i)
return divisors
# Get the greatest of common divisor of a and b
# Euclidean Algorithm
def gcd(a, b):
"""
Get the greatest of common divisor of a and b
params: a, b: integer,
return: integer
"""
a, b = (b, a) if a < b else (a, b)
while b != 0:
r = a % b
# print(a, b, r)
a, b = b, r
return a
# determine whether an integer n is prime
def isprime(n):
"""
Return True if n is prime, or False
params: n, integer
return: True or False
"""
if n > 2 and n % 2 == 0:
return False
limit = int(pow(n, 0.5)) + 1
for i in range(2, limit):
if n % i == 0:
return False
return True
# extended Euclidean Algorithm
def extended_euclidean_algorithm(a, b):
"""
Let a and b be positive integers. Then the integer(not necessarily positive)numbers x and y exist
such that ax + by = gcd(a, b)
params: a, b: positive integer
return: u: tuple --> (gcd(a, b), x, y)
"""
u = (a, 1, 0)
v = (b, 0, 1)
while v[0] != 0:
q = u[0] // v[0]
t = (u[0] % v[0], u[1] - q * v[1], u[2] - q * v[2])
u = v
v = t
return u
# multiplicative inverse
def get_multiplicative_inverse(a, m):
"""
The modulo operation on both parts of equation gives us
ax = 1 (mod m)
Thus, x is the modular multiplicative inverse of a modulo m
params: a, m : integer
return x : integer
"""
if a == 0:
return 0
if a < 0:
a %= m
assert gcd(a, m) == 1, '%d and %d is not coprime.'% (a, m)
_, x, y = extended_euclidean_algorithm(a, m)
if x < 0:
x += m
return x
# modular inverse
# solving equation
def solve_modular_inverse_equation(a, b, p):
"""
The equation a * x = b(mod p), solving the equation to get x
params: a, integer
b, integer
p, integer, gcd(a,p) = 1
return: x: integer, x = b * a ^ (-1) (mod p)
a ^ (-1) mod p : get_multiplicative_inverse(a, p)
"""
assert gcd(a, p) == 1, '%d and %d is not coprime.'% (a, p)
a_inverse = get_multiplicative_inverse(a, p)
x = b * a_inverse % p
return x
# Modular Exponentiation(from right to left)
def get_modular_exponentiation_from_right(a, x, p):
"""
params: a: integer 底数
x: positive integer 指数
p: integer 模数
return: a ^ x mod p: integer
"""
# from right to left
x = bin(x)[2:][::-1]
y = 1
s = a
for i in x:
if i == '1':
y = y * s % p
s = s * s % p
return y
# Modular Exponentiation(from left to right)
def get_modular_exponentiation_from_left(a, x, p):
"""
params: a: integer 底数
x: positive integer 指数
p: integer 模数
return: a ^ x mod p: integer
"""
# from left to right
x = bin(x)[2:]
y = 1
# print(f'x: {x}')
for i in x:
y = y * y % p
if i == '1':
y = y * a % p
return y
# order of a modulo n
def get_order_of_modulo(a, n):
"""
Return the smallest integer i for which
a ^ (i + 1) mod n = a
we call the order of a modulo n
params: a, integer
n, integer
return i, integer
>>> get_order_of_modulo(2, 31)
5
>>> get_order_of_modulo(3, 7)
6
"""
i = 1
while i < n:
assert a ** (i + 1) % n != 0, "No solutions!!\n Because %d ** %d %% %d == 0"%(a, i+1, n)
if a ** (i + 1) % n == a:
return i
i += 1
return 0
# integer generators
def get_smallest_generator(p):
"""
Return the smallest integer generator `g` such that
ord{g, p} = p - 1
from Euler's theorem:
if a is coprime to n, that is, gcd(a, n) =1, then a ^(phi(n)) = 1 mod n;
if p is prime number, the integer between 1 and p, but 1 and p, gcd(g, p) == 1
params: p, integer, prime number
return: g, integer
"""
assert isprime(p), 'p is not prime number.'
divisors = find_divisors(p - 1)
i = 2
while i < p:
for d in divisors:
if i ** d % p == 1:
# print(f'{i} ^ {d} mod {p} == 1')
break
else:
if i ** (p - 1) % p == 1:
return i
i += 1
def find_several_generators(p, amount=10):
"""
Return the several integer generator `g` such that
ord{g, p} = p - 1
params: p, integer, prime number
amount, integer, the amount of produce generators
return: generators, set
"""
assert isprime(p), 'p is not prime number.'
generators = []
divisors = find_divisors(p - 1)
for i in range(2, p-1):
for j in divisors:
if i ** j % p == 1:
break
else:
generators.append(i)
if len(generators) == amount:
return generators
return generators
# get a integer's prime factor
def prime_factorization(n):
"""
Return the integer n's prime factors
param: n, integer
return: factors, list
"""
if isprime(n):
return [1, n]
d = 2
factors = []
while n > 1:
if n % d == 0:
factors.append(d)
n = n // d
else:
d += 1 + d % 2
return factors
|
import numpy as np
from collections import Iterable
def flatten(items):
""" Yield items from any nested iterable; see REF. """
for x in items:
if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
yield from flatten(x)
else:
yield x
def cartesian(arrays, out=None):
""" Generate a cartesian product of input arrays.
Parameters:
arrays (list of array-like): 1-D arrays to form the cartesian product of.
out (ndarray): Array to place the cartesian product in.
Returns:
out (ndarray): 2-D array of shape ``(M, len(arrays))`` containing cartesian products formed of input arrays.
Examples:
>>> cartesian(([1, 2, 3], [4, 5], [6, 7]))
array([[1, 4, 6],
[1, 4, 7],
[1, 5, 6],
[1, 5, 7],
[2, 4, 6],
[2, 4, 7],
[2, 5, 6],
[2, 5, 7],
[3, 4, 6],
[3, 4, 7],
[3, 5, 6],
[3, 5, 7]])
"""
arrays = [np.asarray(x) for x in arrays]
dtype = arrays[0].dtype
n = np.prod([x.size for x in arrays])
if out is None:
out = np.zeros([n, len(arrays)], dtype=dtype)
m = int(n / arrays[0].size)
out[:,0] = np.repeat(arrays[0], m)
if arrays[1:]:
cartesian(arrays[1:], out=out[0:m,1:])
for j in range(1, arrays[0].size):
out[j*m:(j+1)*m,1:] = out[0:m,1:]
return out
def combinations(iterable):
""" Makes combinations out of the input iterable.
Args:
iterable (iterable): The iterable to process
Transforms a dictionary ({name_i: values_i}) into a list of dictionaries structured as:
- each dictionary.values() is an element of the carthesian product of values_i (computed accross every i)
- each dictionary entry is a parameter name-value pair
Transforms a list of values_i into a list of array, where each is an element of the carthesian product of values_i (computed accross every i).
Note:
The array type is inferred from the first array in list!
"""
if isinstance(iterable, list):
return cartesian(iterable)
elif isinstance(iterable, dict):
values = cartesian(iterable.values())
return list(dict(zip(iterable.keys(), val)) for val in values)
else:
raise ValueError("iterable must be a list or a dictionary")
if __name__ == '__main__':
N = np.random.randint(3,5)
A = list(np.random.randint(0,10,np.random.randint(1,4)).tolist() for _ in range(N))
B = dict((str(n), np.random.randint(0,10,np.random.randint(1,4)).tolist()) for n in range(N))
print('A')
for a in A: print(a)
print()
print('B')
for b1, b2 in B.items(): print(b1, b2)
print('combinations(A)')
for ca in combinations(A): print(ca)
print('combinations(B)')
for d in combinations(B): print(d)
|
def verticalizing(str):
for letter in str:
print(letter)
name = str(input("Informe seu nome: ")).strip()
verticalizing(name)
|
class DecTree:
# The set of all attrs in the tree
# Is a set because all attrs in the tree should be unique
attrs = set()
def __init__(self, attr='?', values=[]):
# attr: string stating the attribute this node represents
if not isinstance(attr, str): raise TypeError("attribute argument must be a string")
# values: list of strings representing the values branches can have
if (not isinstance(values, list) # values must be a list
or not all([isinstance(v,str) for v in values])): # all items in values must be strs
raise TypeError("values argument must be a list of strings")
# make sure attr is given if values are given
if attr=='?' and values: raise ValueError("cannot assign values to attribute '?'")
self.attr = attr
self.values = {val:DecTree() for val in values} # new empty tree at end of each value branch
# add attr of this node to global list of attrs that make up this tree
if values: DecTree.attrs.add(self.attr)
def add_node(self, value, child_attr='?', child_values=[]):
# function to assign new attribute node to the end of a value branch
# child must be added to the end of an existing branch
if value not in self.values: raise ValueError(f"'{value}' not a value of '{self.attr}'")
# child attr must not be already in the tree
if child_attr in DecTree.attrs: raise ValueError(f"'{child_attr}' already in tree")
self.values[value] = DecTree(child_attr, child_values)
def get_node(self, attr):
# traverse tree and return node with given attr
if self.attr==attr: return self
for value in self.values:
child = self.values[value]
if child.get_node(attr): return child.get_node(attr)
raise ValueError(f"'{attr}' not in tree")
def __str__(self, level=0):
lines = []
indent = ' '
lines.append(indent*level + self.attr) # print attr of node
for value in self.values:
child = self.values[value]
lines.append(indent*(level+1) + value) # print value branch
lines.append(child.__str__(level+2)) # print child at end of branch
return '\n'.join(lines)
|
from random import randint
def bozosort (items):
while not sorted(items) == items:
switch(items)
return items
def switch(items):
num1 = randint(0, len(items) - 1)
num2 = randint(0, len(items) - 1)
items[num1], items[num2] = items[num2], items[num1]
return items
|
def encrypt (key, plaintext):
return process(key, plaintext, 1)
def decrypt (key, ciphertext):
return process(key, ciphertext, -1)
def process(key, text, sign):
if key is "":
raise ValueError ("Cannot use empty key")
else:
uppercase_key = key.replace(' ', '').upper()
uppercase_text = text.replace(' ', '').upper()
if sign == 1:
length = len(uppercase_text)
actual_key = str(uppercase_key) + str(uppercase_text)
actual_key = actual_key[0:length]
else:
actual_key = uppercase_key
char_in_text = []
extend = (ord('Z') + 1)
j = 0
for i, char in enumerate(uppercase_text):
if (sign == -1):
extend = 0
if (i >= len(key)):
actual_key += (char_in_text[j])
j += 1
position = (ord(char) + extend + (sign * ord(actual_key[i]))) % (ord('Z') + 1)
if (position < ord('A')):
position += (extend - (sign * ord('A')))
char_in_text.append(chr(position))
result = ''.join(char_in_text)
return result
|
def introductions():
print("Use -I am- statements please. ")
namequestion = raw_input("Tell me your name: ")
name = namequestion.replace("I am ", "")
print("Hello, " + name + "!")
agequestion = raw_input("Tell me your age: ")
age = namequestion.replace("I am ", "")
in
troductions()
|
def loops():
word = raw_input("word")
letters = len(word)
for letters in word:
print word
def square(x):
runningtotal = 0
for counter in range(x):
runningtotal = runningtotal + x
return runningtotal
print runningtotal
loops()
square(2)
|
def factorial(x):
total =1
while x>=1:
total *= x
x-=1
print (total)
return total
factorial(10)
|
# final=""
# inp = input("enter a number or exit:")
# while (inp != "exit"):
# final = final+inp+" "
# inp = input("enter a number or exit:")
# print(final)
from getpass import getpass
asdf = input("This is not secure: ")
pw = getpass("This is secure: ")
print("You typed: " + pw)
|
#seconds= remander of the seconds input -_-
#minute=60 seconds
#hour=3600 seconds
s= int(input())
m=s/60
seconds=s%60
hour= m/60
hour=s/3600
print( str(int(hour)) + " hour " + str(int(m)) + " minute " + str(int(seconds)) + " seconds ")
|
import os
import random
from _chromosome import Chromosome
from _expression import Expression
def Selection(population):
#DISPLAY ALL OF THE POPULATION
#SELECT TWO FROM POPULATION FOR CROSSOVER
#RETURN A NEW LIST OF CHROMOSOME
p1 = population[0] # 1ST MOST FIT
random_parent = random.randint(1, len(population) - 1)
p2 = population[random_parent] # PICK A RANDOM SECOND PARENT
new_population = [p1,p2]
return new_population
def Crossover(pivot, c1, c2):
#RETURN TWO CHROMOSOME OBJECTS
C1 = ""
C2 = ""
for i in range(0, pivot):
C1 += c1._info[i]
C2 += c2._info[i]
for i in range(pivot, len(c1._info)):
C1 += c2._info[i]
C2 += c1._info[i]
c1 = Chromosome(C1)
c2 = Chromosome(C2)
return [c1, c2]
def Mutation(mutationRate, c):
#ITERATE THROUGH THE CHROMOSOME, DETERMINE IF A SPECIFIC SPOT NEEDS TO BE REVERSED
if mutationRate > 100: #LIMIT THE RATE OF MUTUATION BY 100%
mutationRate = 100 #IF MUTATION RATE IS GREATER THAN 100%, ASSIGN 100 TO 'mutationRate'
mutatedChromo = ""
for i in range(0, len(c._info)):
x = random.uniform(0, 100) #GENERATE A RANDOM NUMBER
if x <= mutationRate: #IF THE RANDOM NUMBER GENERATED IS LESS THAN OR EQUAL TO THE MUTATION RATE, MUTATE THIS SPOT
m = bool(int(c._info[i])) #TYPECAST AS A BOOLEAN
mutatedChromo += str(int(not m)) #REVERSE THE RESULT, TYPECAST BACK TO STRING AND APPEND
#c._info[i] = str(not m)
else:
mutatedChromo += c._info[i] #SAVE THE ORIGINAL INFO
return mutatedChromo
|
from random import randint
quiz = randint(1, 100)
print("Saya menyimpan angka bulat antara 1 sampai 100. coba tebak")
jawab = 0
count = 1
while jawab != quiz:
jawab = input('Masukkan tebakan ke-{}:>'.format(count))
jawab = int(jawab)
if jawab == quiz:
print('Ya. Anda benar')
elif jawab < quiz:
print('Itu terlalu kecil. Coba lagi')
else:
print('Itu terlalu besar. Coba lagi')
count += 1
|
from random import randint
def log2n(n):
return 1 + log2n(n/2) if (n > 1) else 0
def quiz(angka):
quiz = randint(1, angka)
jawab = 0
count = 1
maks = log2n(angka)
print('Saya menyimpan angka bulat antara 1 sampai {}. anda punya {}x kesempatan. coba tebak'.format(angka, maks))
while jawab != quiz and count <= maks:
jawab = int(input('Masukkan tebakan ke-{}:>'.format(count)))
if jawab == quiz:
print('Ya. Anda benar')
elif jawab < quiz:
print('Itu terlalu kecil. Coba lagi')
else:
print('Itu terlalu besar. Coba lagi')
count += 1
quiz(10000)
# Karena menggunakan konsep Big-O. Dimana yang dipakai
# adalah rumus O(log n) dengan rincian 1 = 1, 2 = 2, 4 = 3, 10 = 4, 100 = 7, 1000=10.
# Di mana log berasal dari pangkat log berbasis 2. Dengan begitu dapat mengetahui jumlah
# maksimal tebakan.
# Untuk pola sendiri:
# apabila ingin menebak angka 70
# a = nilai tebakan pertama // 2
# tebakan selanjutnya = nilai tebakan "lebih dari" + a
# *jika hasil tebakan selanjutnya "kurang dari", maka nilai yang dipakai
# tetap nilai lebih dari sebelumnya*
# a = a // 2
# Simulasi
# tebakan ke 1: 50 (mengambil nilai tengah) jawaban= "lebih dari itu"
# tebakan ke 2: 75 (dari 50 + 25) jawaban = "kurang dari itu"
# tebakan ke 3: 62 (dari 50 + 12) jawaban = "lebih dari itu"
# tebakan ke 4: 68 (dari 62 + 6) jawaban = "lebih dari itu"
# tebakan ke 5: 71 (dari 68 + 3) jawaban = "kurang dari itu"
# tebakan ke 6: 69 (dari 68 + 1) jawaban = "lebih dari itu"
# tebakan ke 7: antara 71 dan 69 hanya ada 1 angka = 70!!!
|
def breadth_first_search_tuples(problem):
"""[Figure 3.11]"""
node = Node(problem.initial)
if problem.goal_test(node.state):
return node
frontier = FIFOQueue()
frontier.append(node)
explored = set()
while frontier:
node = frontier.pop()
explored.add(tuple(node.state)) #tuples!
for child in node.expand(problem):
if tuple(child.state) not in explored and child not in frontier: #tuples tuples!
if problem.goal_test(child.state):
return child
frontier.append(child)
return None
|
# Py_Ch_10_1.py
# Authors: Sam Coon and Tyler Kapusniak
# Date: 3/4/15
from tkinter import *
class Application(Frame):
""" GUI application that creates a story based on user input. """
def __init__(self, master):
""" Initialize Frame. """
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
""" Create widgets to get story information and to display story. """
# create instruction label
Label(self,
text = "Enter information for a new story"
).grid(row = 0, column = 0, columnspan = 2, sticky = W)
# create a label and text entry for the name of a person
Label(self,
text = "Person: "
).grid(row = 1, column = 0, sticky = W)
self.person_ent = Entry(self)
self.person_ent.grid(row = 1, column = 1, sticky = W)
# create a label and text entry for a plural noun
Label(self,
text = "Plural Noun:"
).grid(row = 2, column = 0, sticky = W)
self.noun_ent = Entry(self)
self.noun_ent.grid(row = 2, column = 1, sticky = W)
# create a label and text entry for a verb
Label(self,
text = "Verb:"
).grid(row = 3, column = 0, sticky = W)
self.verb_ent = Entry(self)
self.verb_ent.grid(row = 3, column = 1, sticky = W)
# create a label for adjectives check buttons
Label(self,
text = "Adjective(s):"
).grid(row = 4, column = 0, sticky = W)
# create itchy check button
self.is_itchy = BooleanVar()
Checkbutton(self,
text = "itchy",
variable = self.is_itchy
).grid(row = 5, column = 0, sticky = W)
# create joyous check button
self.is_joyous = BooleanVar()
Checkbutton(self,
text = "joyous",
variable = self.is_joyous
).grid(row = 6, column = 0, sticky = W)
# create electric check button
self.is_electric = BooleanVar()
Checkbutton(self,
text = "electric",
variable = self.is_electric
).grid(row = 7, column = 0, sticky = W)
# create a label for body parts radio buttons
Label(self,
text = "Body Part:"
).grid(row = 4, column = 1, sticky = W)
# create variable for single, body part
self.body_part = StringVar()
self.body_part.set(None)
# create body part radio buttons
body_parts = ["bellybutton", "big toe", "medulla oblongata"]
row = 5
for part in body_parts:
Radiobutton(self,
text = part,
variable = self.body_part,
value = part
).grid(row = row, column = 1, sticky = W)
row += 1
# create a submit button
Button(self,
text = "Click for story",
command = self.tell_story
).grid(row = 8, column = 0, sticky = W)
self.story_txt = Text(self, width = 75, height = 10, wrap = WORD)
self.story_txt.grid(row = 9, column = 0, columnspan = 4)
def tell_story(self):
""" Fill text box with new story based on user input. """
# get values from the GUI
person = self.person_ent.get()
noun = self.noun_ent.get()
verb = self.verb_ent.get()
adjectives = ""
if self.is_itchy.get():
adjectives += "itchy, "
if self.is_joyous.get():
adjectives += "joyous, "
if self.is_electric.get():
adjectives += "electric, "
body_part = self.body_part.get()
# create the story
story = "The famous explorer "
story += person
story += " had nearly given up a life-long quest to find The Lost City of "
story += noun.title()
story += " when one day, the "
story += noun
story += " found "
story += person + ". "
story += "A strong, "
story += adjectives
story += "peculiar feeling overwhelmed the explorer. "
story += "After all this time, the quest was finally over. A tear came to "
story += person + "'s "
story += body_part + ". "
story += "And then, the "
story += noun
story += " promptly devoured "
story += person + ". "
story += "The moral of the story? Be careful what you "
story += verb
story += " for."
# display the story
self.story_txt.delete(0.0, END)
self.story_txt.insert(0.0, story)
# main
root = Tk()
root.title("Mad Lib")
app = Application(root)
root.mainloop()
|
## QUESTÃO 6 ##
# Escreva um programa que calcule a porcentagem de nucleotídeos A, C, G e T em
# uma cadeia de DNA informada pelo usuário. Indicar também a quantidade e a
# porcentagem de nucleotídeos inválidos.
##
##
# A sua resposta da questão deve ser desenvolvida dentro da função main()!!!
# Deve-se substituir o comado print existente pelo código da solução.
# Para a correta execução do programa, a estrutura atual deve ser mantida,
# substituindo apenas o comando print(questão...) existente.
##
def main():
# Programa que lê uma sequência de DNA e retorna a sua composição e quantidade de inválidos.
sequencia = str(input('Digite a cadeia de DNA: ')).upper()
Total = len(sequencia)
A = (sequencia.count('A') / Total) * 100
T = (sequencia.count('T') / Total) * 100
C = (sequencia.count('C') / Total) * 100
G = (sequencia.count('G') / Total) * 100
invalido = 100 - (A + T + C + G)
print('''Sequência total: {0}\n
Adenina: {1}\n
Timina: {2}\n
Citosina: {3}\n
Guanina: {4}\n
Inválidos: {5}
Porcentagens:\n
Adenina: {6:.2f}\n
Timina: {7:.2f}\n
Citosina: {8:.2f}\n
Guanina: {9:.2f}'''.format(Total, sequencia.count('A'), sequencia.count('T'), sequencia.count('C'),
sequencia.count('G'), invalido, A, T, C, G))
if __name__ == '__main__':
main()
|
import math
def scical(a, op):
if (op == 'sin'):
print("sin({x}) = {y:1.2f}".format(x=a , y=math.sin(math.radians(a))))
elif (op == 'log'):
print("log({x}) = {y:1.2f}".format(x=a , y=math.log10(a)))
elif (op == 'sqrt'):
print("sqrt({x}) = {y:1.3f}".format(x=a , y=math.sqrt(a)))
else:
print("Operation NOT found...!!!")
|
from string import ascii_uppercase as A
"""
KSum implementaiont and Kadane's Algorithm for max subarray.
KSum remarks: Translation from
https://www.sigmainfy.com/blog/k-sum-problem-analysis-recursive-implementation-lower-bound.html
"""
def firstDuplicate(a):
"""
:type a: list[int]
:rtype n: char
"""
index = 0
m = {}
for num in a :
#store (key, index) pairs if new
if num not in m:
m.setdefault(num, [index])
#number exist already and first occurance exist
else:
m[num].append(index)
index = index + 1
key_set = list( m.keys() )
# trim table and
for key in key_set:
#if unique occurance, remove... not significant
if len(m[key]) < 2:
m.pop(key, None)
#duplicate, remove first index
else:
m[key].pop(0)
min = len(a) + 1
n = 0
for key in m:
if m[key][0] < min:
min = m[key][0]
n = key
if min == ( len(a) + 1):
m = -1
return n
def firstNonRepeatChar(s):
"""
first non-repeating character
"""
if len(s) < 2:
return
sum = 0
ascii_set = []
c = None
for char in s:
c = ord(char)
sum = sum + c
if c not in ascii_set:
ascii_set.append(c)
for num in ascii_set:
n = sum % num
k = (sum - num) / n
check_sum = sum
c = chr( check_sum)
print("n: " + str(n) + " k: "+str(k) + " check_sum: " + str(check_sum))
print(" charachter: " + c)
def twoSum(l, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
table = {}
for i in l:
table.setdefault( (target -i), i)
result = []
for key in table:
if key in l:
result.append( [table[key],key] )
return result
def threeSum( list_t, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
table = {}
result = []
for i in list_t:
table.setdefault(target-i, i)
key_val = 0
for val in table:
for num in list_t:
key_val = val - num
if key_val in list_t:
tuple4=[key_val, num, table[val] ]
tuple4.sort()
if tuple4 not in result:
result.append(tuple4)
for quadruple in result:
print(quadruple)
def threeSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
nums.sort()
result = []
i,j = 0,0
N= len(nums)
for i in range(N):
if i > 0 and nums[i] == nums[i-1]:
continue
l, r = i+1, N-1
target = nums[i]*-1
while( l < r):
if target == nums[l]+nums[r]:
result.append( [nums[i], nums[l], nums[r]])
l += 1
while l < r and nums[l] == nums[l - 1]: l += 1
elif nums[l] + nums[r] < target:
l+=1
else:
r -=1
return result
def KSum(nums, k, target, start):
"""
:type nums: List[int]
:type target: int
:type start: int
:rtype: List[List[int]]
"""
results = []
if k == 2:
i = start
j = len(nums) -1
while i < j:
if i > start and nums[i] == nums[i-1]:
i+=1
continue
if (nums[i] + nums[j]) == target:
t = [ nums[i], nums[j]]
i+=1; j-=1
results.append(t)
elif (nums[i]+nums[j] ) > target:
j-=1
else:
i+=1
return results
for i in range(start, len(nums)):
#if i > start and nums[i] == nums[i-1]:
# continue
k_sum_list = KSum(nums, k-1, target - nums[i], i+1)
for tuple_n in k_sum_list:
t = [nums[i]]
t +=tuple_n
t.sort()
if t not in results:
results.append(t)
return results
def maxSubArray(A):
"""
"Kadane's algorithm
"
" list A
"""
max_temp, max_global = A[0], A[0]
start, end, n = 0,1,0
for i in range(1, len(A)):
n = A[i]
max_temp = max(n, max_temp + n)
if max_temp == n:
start = i
max_global = max( max_global, max_temp)
if max_global == max_temp:
end = i
if end < start:
start = A.index(max_global)
end = start
print("Subarray max: "+ str(max_global)+", <start,end>=< "+str(start)+", "+str(end) +">")
def test():
k = [1,1,2,1,2,3,4,5,6,7]
k2 = [1,0,-1,0,-2,2]
k2.sort()
l = KSum(k, 4, 10, 0)
l2 = KSum(k2, 4, 0, 0)
for item in l2:
print(item)
if __name__ == "__main__":
test()
|
import argparse
import os
from pathlib import Path
import shutil
parser = argparse.ArgumentParser(description='Find files in the src, and add them to the dst but inside a folder')
parser.add_argument('--src', help="The location to search for files", required=True)
parser.add_argument('--dst', help="The location to create the directory and place the files", required=True)
args = parser.parse_args()
print(args.src, args.dst)
for root, dirs, files in os.walk(args.src):
for name in files:
destination_directory = Path(name).stem
destination_file = name
dst_file_path = '{}/{}/{}'.format(args.dst, destination_directory, destination_file)
src_size = Path(os.path.join(root, name)).stat().st_size
dst_file = Path(dst_file_path)
if dst_file.exists():
dst_size = Path(dst_file).stat().st_size
else:
dst_size = 0
print("{} exists: {}, Src size: {}, Dst size: {}".format(dst_file, dst_file.exists(), src_size, dst_size))
if not dst_file.exists() or dst_size != src_size:
print("Will create '{}' from {}".format(dst_file_path,
os.path.join(root, name)))
print("Copying...")
os.makedirs("{}/{}".format(args.dst, destination_directory), exist_ok=True)
shutil.copy(os.path.join(root, name), "{}/{}/{}".format(args.dst, destination_directory, destination_file))
print("Done copying...")
else:
print("Destination file exists and is the same size as the source")
|
# 哈夫曼算法
from heapq import heapify, heappush, heappop
from itertools import count
def huffman(seq, frq):
num = count()
print(num)
trees = list(zip(frq, num, seq))
print(trees)
heapify(trees)
while len(trees) > 1:
fa, _, a = heappop(trees)
fb, _, b = heappop(trees)
n = next(num)
heappush(trees, (fa+fb, n, [a, b]))
print()
print(trees)
return trees[0][-1]
def main():
seq = "abcdefghi"
frq = [4, 5, 6, 9, 11, 12, 15, 16, 20]
print(huffman(seq, frq))
if __name__ == "__main__":
pass
main()
|
def bubble_sort(array):
for i in range(len(array))[::-1]:
for j in range(i):
if array[j] > array[j+1]:
array[j], array[j+1] = array[j+1], array[j]
print(array)
# return array
if __name__ == '__main__':
array = [1, 2, 3, 6, 5, 4]
bubble_sort(array)
|
'''
All the functions linked to the prediction behaviour of the robot
'''
import algebra as alg
from math import sqrt,cos,sin,acos,pi,atan2
import numpy as np
deltaT = 0.4 #s
def predictionNextPosition(linearSpeed,position):
'''
Return the predicted next position of the robot
Considering its current position and speed
'''
distance = np.dot(linearSpeed,deltaT)
return np.add(position,distance)
def neareastPoint(begin,end,point):
'''
Return the neareast point of the robot on a certain subPath (segment)
using the orthogonal projection
'''
from pathFollowingAlgorithm import radius
v = np.subtract(end,begin)
normV = np.linalg.norm(v)
#Compute the nearest point coordinate thanks to orthogonal projection
distance = ((point[0]-begin[0])*v[0] + (point[1]-begin[1])*v[1])/normV
xn = begin[0] + (distance/normV)*v[0]
yn = begin[1] + (distance/normV)*v[1]
distanceToPath = np.linalg.norm(np.subtract(point,[xn,yn]))
#if the robot is too far from the path
if abs(distanceToPath) > radius :
return[xn,yn] # return its nearest point coordinate
else :
return point #return its coordinate
def smallestDistance(begin,end,point):
'''
Return the smallest distance between the robot and the subpath
as well as the coordinate of the nearest point
'''
v = alg.euclideanVector(begin,end)
normV = np.linalg.norm(v)
#Compute the nearest point coordinate thanks to orthogonal projection
distance = ((point[0]-begin[0])*v[0] + (point[1]-begin[1])*v[1])/normV
xn = begin[0] + (distance/normV)*v[0]
yn = begin[1] + (distance/normV)*v[1]
n = [xn,yn]
dx = xn - point[0]
dy = yn - point[1]
return [sqrt(dx**2+dy**2),n]
'''Compute the position of the target using the neareast point on a subtrajectory
and its euclidean vector'''
def positionTarget(neareastPoint,euclideanvector):
from pathFollowingAlgorithm import deltaD
euclideanvector = alg.unitVector(euclideanvector)
vDistance = np.dot(euclideanvector,deltaD)
return np.add(neareastPoint,vDistance)
'''Return the vector between the robot and its target'''
def orientationTarget(pRobot,pTarget):
return alg.unitVector(alg.euclideanVector(pRobot,pTarget))
'''Return the closest subPath from the robot'''
def closestPath(lastSubPath,pathPositions,point):
[number,closest] = [-1,1000] #path number, distance to robot
#Every path after the one currently considered and except the last one
if lastSubPath < len(pathPositions)-2:
for i in range(lastSubPath,(len(pathPositions)-1)):
[d,n] = smallestDistance(pathPositions[i],pathPositions[i+1],point)
t = positionTarget(n,alg.euclideanVector(pathPositions[i],pathPositions[i+1]))
#The robot should follow a close path as much as possible
begin = pathPositions[lastSubPath]
end = pathPositions[lastSubPath+1]
if i == lastSubPath and alg.is_close_to_path(n,end,begin):
if d < closest+1 :
closest = d
number = i
'''else :
#If the closest paths are not ideal, let's consider the other paths
if d < closest+1 and alg.is_close_to_path(n,pathPositions[i],pathPositions[i+1]):
closest = d
number = i'''
if number != -1 and closest != 1000: #if the robot found a patht to follw
[d,n] = smallestDistance(pathPositions[number],pathPositions[number+1],point)
return number
else : # we move to the next path
return lastSubPath+1
else : #we stay on the last path
return lastSubPath
if __name__ == "__main__":
begin = [0,0]
end = [10,10]
p = [5,5]
linearSpeed = 50
p = predictionNextPosition(linearSpeed,p)
n = neareastPoint(begin,end,p)
d = smallestDistance(begin,end,p)
t = positionTarget(n,np.subtract(end,begin))
o = orientationTarget(p,t)
|
# -*- coding: utf-8 -*-
# Filename : matrix.py
# Author : Hao Limin
# Date : 2020-03-15
# Email : [email protected]
# Python : 3.7.5
"""
Define Matrix and Vector structure.
Gnd(number = 0) must be at the first row and first column,
Matrix and Vector's size is (n) x (n), (n) x 1.
Matrix is not sparse matrix.
dtype meansing data type, real or complex.
"""
import numpy as np
from define import const
class Matrix():
def __init__(self, size, dtype):
self.set_size(size)
self.set_dtype(dtype)
self.mat = np.zeros((self.__size, self.__size), self.__dtype)
def set_size(self, size):
size = int(size)
if size <= 0:
size = 1
self.__size = size
def get_size(self):
return self.__size
def set_dtype(self, dtype):
if dtype != 'float' and dtype != 'complex':
self.__dtype = 'complex'
else:
self.__dtype = dtype
def get_dtype(self):
return self.__dtype
def set_value(self, row, col, value):
assert 0 <= row < self.__size
assert 0 <= col < self.__size
self.mat[row, col] = value
def add_value(self, row, col, value):
assert 0 <= row < self.__size
assert 0 <= col < self.__size
self.mat[row, col] += value
def get_value(self, row, col):
assert 0 <= row < self.__size
assert 0 <= col < self.__size
return self.mat[row, col]
"""
Set all elements to zero.
"""
def clear(self):
if self.__dtype == 'float':
self.mat[:] = 0
elif self.__dtype == 'complex':
self.mat[:] = 0 + 0j
def print_to_screen(self):
if self.__dtype == 'float':
width = const.PRINT_FLOAT_WIDTH
else:
width = const.PRINT_COMPLEX_WIDTH
print("Modified Nodal Matrix")
# The first line
line = "{0:<{1}s}".format("index", width)
for i in range(self.__size):
line += "{0:<{1}d}".format(i, width)
print(line)
# Print every row.
for i in range(self.__size):
line = "{0:<{1}d}".format(i, width)
for j in range(self.__size):
if self.__dtype == 'float':
line += "{0:<{1}.2f}".format(self.get_value(i, j), width)
else:
line += "{0.real:<{1}.2f}{0.imag:<{1}.2f}j".format(self.get_value(i, j), width)
print(line)
def dump_to_file(self):
pass
class Vector():
def __init__(self, size, dtype):
self.set_size(size)
self.set_dtype(dtype)
self.vec = np.zeros((self.__size, 1), self.__dtype)
self.vec[0, 0] = 0
def set_size(self, size):
size = int(size)
if size <= 0:
size = 1
self.__size = size
def get_size(self):
return self.__size
def set_dtype(self, dtype):
if dtype != 'float' and dtype != 'complex':
self.__dtype = 'complex'
else:
self.__dtype = dtype
def get_dtype(self):
return self.__dtype
def set_value(self, row, value):
assert 0 <= row < self.__size
self.vec[row, 0] = value
def add_value(self, row, value):
assert 0 <= row < self.__size
self.vec[row, 0] += value
def get_value(self, row):
assert 0 <= row < self.__size
return self.vec[row, 0]
"""
Set all elements to zero.
"""
def clear(self):
if self.__dtype == 'float':
self.vec[:] = 0
elif self.__dtype == 'complex':
self.vec[:] = 0 + 0j
def print_to_screen(self, label = "Vector"):
if self.__dtype == 'float':
width = const.PRINT_FLOAT_WIDTH
else:
width = const.PRINT_COMPLEX_WIDTH
print(label)
# The first line.
line = "{0:<{1}s}".format("index", width)
line += "{0:<{1}d}".format(0, width)
print(line)
# Print every row.
for i in range(self.__size):
line = "{0:<{1}d}".format(i, width)
if self.__dtype == 'float':
line += "{0:<{1}.2f}".format(self.get_value(i), width)
else:
line += "{0.real:<{1}.2f}{0.imag:<{1}.2f}j".format(self.get_value(i), width)
print(line)
def dump_to_file(self):
pass
|
#!/usr/bin/python
import turtle
import math
from collections import deque
def main_triangle():
t.begin_fill()
for i in range(1,4):
if i == 1 :
todo.append(t.position())
if i == 2 :
todo.append(t.position()-(side/2,0))
if i == 3 :
#print t.position()
#print math.sqrt((side/2)**2-(side/4)**2)
todo.append(t.position()+(-(side/4),math.sqrt((side/2)**2-(side/4)**2)))
t.forward(side)
t.right(120)
t.end_fill()
def draw_triangle(side):
t.penup()
top = todo.popleft()
#print top
t.goto(top)
t.pendown()
for i in range(1,4):
if i == 1 :
todo.append(t.position())
if i == 2 :
todo.append(t.position()-(side/2,0))
if i == 3 :
#print t.position()
#print math.sqrt((side/2)**2-(side/4)**2)
todo.append(t.position()+(-(side/4),math.sqrt((side/2)**2-(side/4)**2)))
t.forward(side)
t.right(120)
t = turtle.Turtle()
t.speed("fast")
window = turtle.Screen()
side = 240
todo = deque([])
t.color("white")
main_triangle()
n=1
t.color("green")
while (todo):
side = side / 2
if n>=3:
t.color("green")
t.begin_fill()
for i in range(1,(3**n+1)):
#print side, i
draw_triangle(side)
n = n + 1
#print todo.pop()
if ( 3**n > 81 ):
t.end_fill()
exit(1)
window.exitonclick()
|
''' Python in its language defines an inbuilt module “keyword” which handles certain operations related to keywords.
A function “iskeyword()” checks if a string is keyword or not. '''
import keyword # Importing Keyword for Keyword operations
# Initializing Strings For testing
s = "for"
s1 = "geeksforgeeks"
s2 = "elif"
s3 = "elseif"
s4 = "nikhil"
s5 = "assert"
if keyword.iskeyword(s):
print(s + " is a Keyword")
else:
print(s + " is not a Keyword")
if keyword.iskeyword(s1):
print(s1 + " is a Keyword")
else:
print(s1 + " is not a Keyword")
if keyword.iskeyword(s2):
print(s2 + " is a Keyword")
else:
print(s2 + " is not a Keyword")
if keyword.iskeyword(s3):
print(s3 + " is a Keyword")
else:
print(s3 + " is not a Keyword")
if keyword.iskeyword(s4):
print(s4 + " is a Keyword")
else:
print(s4 + " is not a Keyword")
if keyword.iskeyword(s5):
print(s5 + " is a Keyword")
else:
print(s5 + " is not a Keyword")
'''Printing List of all Keywords'''
print(keyword.kwlist) # USing Kwlist to print all the keywords
# Print without NewLine In Python
print("geeks", end=" ")
print("Geeks For Geeks")
a = [1, 2, 3, 4]
for i in range(4):
print(a[i], end=" ")
''' One Liner If Else statement in Python Instead of conditional Operator(?) '''
a = 1 if 20 > 10 else 0
print(a)
'''Decision makig Statements in python::--
if statement
if..else statements
nested if statements
if-elif ladder
Examples:::::
'''
i = 10
if i < 15:
print("Hello World")
j = 20
if (j < 15):
print ("i is smaller than 15")
print ("i'm in if Block")
else:
print ("i is greater than 15")
print ("i'm in else Block")
print ("i'm not in if and not in else Block")
i = 10
if i == 10:
# First if statement
if i < 15:
print("i is smaller than 15") # Nested - if statement Will only be executed if statement above it is true
if i < 12:
print("i is smaller than 12 too")
else:
print("i is greater than 15")
i = 20
if i == 10:
print("i is 10")
elif i == 15:
print("i is 15")
elif i == 20:
print("i is 20")
else:
print("i is not present")
|
#coding=utf-8
import en
otherwordlist = []
def simplify_word(a):
try:#测试是否为动词,如果是则返回
en.is_verb(en.verb.present(a))
return en.verb.present(a)
except:#否则继续检查
pass
#测试是否是名词
if en.is_noun(en.noun.singular(a)):
return en.noun.singular(a)
#如果已经可以判断是名词,动词,形容词,副词,连词
if en.is_noun(a) or en.is_verb(a) or en.is_adjective(a) or en.is_adverb(a) or en.is_connective(a):
return a
otherwordlist.append(a)
return a
|
import random
import matplotlib.pyplot as plt
from matplotlib import rc
from math import sin, pi
def main():
# gx #
def g(x):
return sin(x*pi)
# end:gx #
# problem_1 #
r = 0.1
for x_0 in (random.random() for i in range(10)):
plt.plot(list(logistic_generator(g, r, x_0, 11)), '.--')
plt.xlabel('$n$'); plt.ylabel('$x^*$')
plt.tight_layout()
plt.savefig(f'p9.1_{r}.eps'); plt.clf()
# plt.show()
r = 0.5
for x_0 in (random.random() for i in range(10)):
plt.plot(list(logistic_generator(g, r, x_0, 15)), '.--')
plt.xlabel('$n$'); plt.ylabel('$x^*$')
plt.tight_layout()
plt.savefig(f'p9.1_{r}.eps'); plt.clf()
# plt.show()
# end:problem_1 #
# # problem_2 #
N = 150
rs = [i/N for i in range(int(0.72*N))]
xs = []
for r in rs:
x_0 = random.random()
it = logistic_generator(g, r, x_0,1000)
for i in range(999):
next(it)
xs.append(next(it))
plt.plot(rs, xs, '.--')
plt.xlabel('$r$'); plt.ylabel('$x^*$')
plt.tight_layout()
plt.savefig(f'p9.2_{r}.eps'); plt.clf()
# plt.show()
# end:problem_2 #
# problem_3 #
r = 0.82
for x_0 in (random.random() for i in range(3)):
plt.plot(list(logistic_generator(g, r, x_0,50)), '.--')
plt.xlabel('$n$'); plt.ylabel('$x^*$')
plt.tight_layout()
plt.savefig(f'p9.3_{r}.eps'); plt.clf()
# plt.show()
# end:problem_3 #
# problem_4 #
N = 150
rs += [i/N for i in range(int(0.72*N), int(0.831*N))]
for r in rs:
x_0 = random.random()
total = 1000
it = logistic_generator(g, r, x_0,total)
for i in range(total-2):
next(it)
obj = list(set(it))
plt.plot([r]*len(obj),obj, '.', c='C0')
plt.xlabel('$r$'); plt.ylabel('$x^*$')
plt.tight_layout()
plt.savefig(f'p9.4_{r}.eps'); plt.clf()
# plt.show()
# end:problem_4 #
# problem_5 #
r = 0.84
plt.plot(list(logistic_generator(g, r, random.random(), 250)), '.')
plt.xlabel(f'$n$, $r={r}$'); plt.ylabel('$x^*$')
plt.tight_layout()
plt.savefig(f'p9.5_{r}.eps'); plt.clf()
# plt.show()
r = 0.86
plt.plot(list(logistic_generator(g, r, random.random(), 250)), '.')
plt.xlabel(f'$n$, $r={r}$'); plt.ylabel('$x^*$')
plt.tight_layout()
plt.savefig(f'p9.5_{r}.eps'); plt.clf()
# plt.show()
# mid:problem_5 #
N = 400
rs = [i/N for i in range(1*N)]
speeds = []
for r in rs:
speeds.append(converge_speed(g, r))
plt.plot(rs, speeds, '.--')
plt.xlabel('$r$'); plt.ylabel('Converging Speed')
plt.tight_layout()
plt.savefig('p9.5_speed_line.eps'); plt.clf()
# plt.show()
# end:problem_5 #
# problem_6 #
N = 300
total = 10000
ry = 1
count = 0
for px, py in zip(
[0, 0.317, 0.719, 0.8328, 0.85648],
[0, 0, 0.645, 0.8205, 0.85650]
):
rs = [px + i*(ry-px)/N for i in range(N)]
for r in rs:
x_0 = random.random()
it = logistic_generator(g, r, x_0, total)
for i in range(total-128):
next(it)
obj = list(set(it))
plt.plot([r]*len(obj), obj, '.', c='C0')
plt.xlabel('$r$' + (f', from $T={2**(count-1)}$ to {2**count}' if count else ''))
plt.ylabel('$x^*$')
margin = (max(obj) - py)/50
plt.ylim(top=max(obj)+margin, bottom=py-margin)
plt.tight_layout()
plt.savefig(f'p9.6_{ry}_{count}.eps'); plt.clf()
# plt.show()
count += 1
ry = 0.86557934
count = 0
for px, py in zip(
[0, 0.317, 0.719, 0.8328, 0.85848, 0.864062,
0.865252, 0.8655092, 0.8655637],
[0, 0, 0.645, 0.8205, 0.85650, 0.863745,
0.865201, 0.865501, 0.8655625]
):
rs = [px + i*(ry-px)/N for i in range(N)]
for r in rs:
x_0 = random.random()
it = logistic_generator(g, r, x_0, total)
for i in range(total-2*1024):
next(it)
obj = list(set(it))
plt.plot([r]*len(obj), obj, '.', c='C0')
plt.xlabel(
'$r$' + (f', from $T={2**(count-1)}$ to {2**count}' if count else ''))
plt.ylabel('$x^*$')
margin = (max(obj) - py)/50
plt.ylim(top=max(obj)+margin, bottom=py-margin)
plt.tight_layout()
plt.savefig(f'p9.6_{ry}_{count}.eps'); plt.clf()
# plt.show()
count += 1
# end: problem_6
# problem_7
rs = [0.317, 0.719, 0.8328, 0.85848,
0.864062, 0.865252, 0.8655092, 0.8655637]
delta = [n - p for n, p in zip(rs[1:], rs[:-1])]
Fs = [p/n for n, p in zip(delta[1:], delta[:-1])]
print(sum(Fs)/len(Fs))
print(delta)
print(Fs)
# log_gen #
def logistic_generator(g, r, x_0, n=50):
'''g: function, r, x_0, n -> generator of Logistic f(x) = r*g(x)
the iteration will repeat `n' times
'''
for i in range(n):
yield x_0
x_0 = r*g(x_0)
# end:log_gen #
# converge_speed #
def converge_speed(g, r, n=30000, skip=5):
'''g: function, r -> converge speed of Logistic f(x) = r*g(x)
for series with cycle other than 1, this speed is defined as that
of each cycle.
n: calculate the series till n
'''
# find cycle T
it = logistic_generator(g, r, random.random(), n)
lst = list(it)
T = len(set(lst[-512:]))
# find x*
x_star = lst[skip+((n-skip)//T-1)*T]
# get sub series
res = []
old_error = lst[skip] - x_star
for i in range(1, 50):
error = lst[skip+i*T] - x_star
if error:
res.append(abs(error/old_error))
old_error = error
else:
break
res = sum(res)/len(res) if res else 0
return res if res <= 1 else 1
# end:converge_speed #
if __name__ == '__main__':
main()
|
#!/usr/bin/python
import textwrap
def find_spaces(string_to_check):
"""Returns a list of string indexes for each string this finds.
Args:
string_to_check; string: The string to scan.
Returns:
A list of string indexes.
"""
spaces = list()
for index, character in enumerate(string_to_check):
if character == ' ':
spaces.append(index)
return spaces
def pad_line(string_to_pad, width):
"""Pads a string to a specified width.
Args:
string_to_pad; string: The string to pad.
width; integer: The length to pad the string to.
Returns:
A string padded to the appropriate length.
"""
# Handles the case where the string is already at the appropriate length.
if len(string_to_pad) >= width:
return string_to_pad
# I perform a list conversion so I can easily insert elements at an
# arbitrary point.
string_to_pad = list(string_to_pad)
spaces = find_spaces(string_to_pad)
# The space offset keeps track of how the list might grow.
space_offset = 0
# I admit this isn't the most elegant implementation.
while len(string_to_pad) < width:
for space in spaces:
if len(string_to_pad) < width:
string_to_pad.insert(space + space_offset, ' ')
space_offset += 1
return ''.join(string_to_pad)
def justify_string(width, string_to_justify):
"""Takes a string and justifies it according to the width provided.
I admit the use of textwrap might miss the spirit of this exercise, but
I am prepared to discuss why I chose textwrap and some of the considerations
I was making.
Args:
width; integer: The column width to justify the string to.
string_to_justify; string: The string to justify.
Returns:
A list of each justified line as a different element in the array.
"""
# Handles the case where the string does not need justification.
if len(string_to_justify) < width:
return string_to_justify
output = list()
lines_to_process = textwrap.wrap(string_to_justify, width)
for i, line in enumerate(lines_to_process):
# The -1 is because len() returns a non-zero padded string length which
# can result in IndexErrors.
if i < len(lines_to_process) - 1:
output.append(pad_line(line, width))
else:
output.append(line)
return output
|
class Person():
def __init__(self,name,age,address,sal):
self.name = name
self.age = age
self.address = address
self.sal = sal
self.company = 'TCS'
self.branch = 'Noida'
def showDetails(self):
print("Parent Class Call")
print("Welcome to {}".format(self.company))
print("Your branch is {}".format(self.branch))
class Emp(Person):
def __init__(self,name,age,address,sal):
super().__init__(name,age,address,sal)
def showPerson(self):
print("Name : {}".format(self.name))
print("Age : {}".format(self.age))
print("Address : {}".format(self.address))
print("Salary : {}".format(self.sal))
def showDetails(self):
print("Child Class Call")
print("Welcome to {}".format(self.company))
print("Your branch is {}".format(self.branch))
emp = Emp('Ram',30,'Delhi',45000)
emp.showDetails()
emp.showPerson()
|
'''
num = int(input("Enter a number : "))
flag = True
for i in range(2,num):
if num % i == 0:
# print("Not Prime")
flag = True
break
else:
# print("Prime Number")
flag = False
if flag:
print("Not Prime")
else:
print("Prime")
'''
num = int(input("Enter a number : "))
flag = True
for i in range(2,num):
if num % i == 0:
print("Not Prime")
break
else:
print("Prime Number")
|
import threading
def job_1():
print("Job_1 Started")
for i in range(100000):
for j in range(10000):
k = i + j
print("Completed {} iterations".format(k))
print("Job_1 Completed")
def job_2():
print("Job_2 Started")
for i in range(1000):
for j in range(100):
k = i + j
print("Completed {} iterations".format(k))
print("Job_2 Completed")
t1 = threading.Thread(target=job_1)
t2 = threading.Thread(target=job_2)
t1.start()
t2.start()
|
#! /usr/bin/python
x = ['a', 'b', 'c']
for i in range(len(x)):
print(f'x[{i}]={x[i]}')
for i, name in enumerate(x, 1):
print(f'{i}th element = {name}')
for i in x:
print(i)
|
#! /usr/bin/python
# Functions to implement
# __len__, is_empty, is_full, push, pop,
# peek, clear, find, count, __contains__, dump
# Expection handling (Empty, Full)
from typing import Any
class FixedStack:
class Empty(Exception):
pass
class Full(Exception):
pass
def __init__(self, capacity: int=256)->None:
self.stk=[None]*capacity
self.capacity=capacity
self.ptr=0
def __len__(self)->int:
return self.ptr
def is_empty(self)->bool:
return self.ptr <= 0
def is_full(self)->bool:
return self.ptr >= self.capacity
def push(self, value: Any)->None:
if self.is_full:
raise self.Full
self.stk[self.ptr] = value
self.ptr += 1
def pop(self)->Any:
if self.is_empty:
raise self.Empty
self.ptr -= 1
return self.stk[self.ptr]
def peek(self)->None:
if self.is_empty:
raise self.Empty
return self.stk[self.ptr-1]
def clear(self)->None:
self.ptr = 0
def find(self, value:Any)->Any:
if self.is_empty:
raise self.Empty
for i in range(self.ptr-1, -1, -1):
if self.stk[i] == value:
return i
return -1
def count(self, value:Any)->int:
c = 0
for i in range(self.ptr-1, -1, -1):
if self.stk[i] == value:
c += 1
return c
def __contains__(self, value)->bool:
# for i in range(self.ptr-1, -1, -1):
# if self.stk[i] == value:
# return True
# return False
return self.count(value) > 0
def dump(self)->None:
if self.is_empty():
print("stack is empty.")
for i in range(self.ptr):
# print(f'{self.stk[i]} ')
print(self.stk[:self.ptr])
|
##########################################################
# Homework 1 Leap Year Code
# CS 362
# Virginia Link
# 01/14/2021
##########################################################
print("Please enter a year to check: ")
#Get user input
year = int(input())
#1. Check if evenly divisible by 4
if (year % 4):
#2. Check if evenly divisible by 100
if (year % 100):
#3. Check if evenly divisible by 400
if (year % 400):
print("%s is not a leap year :(" %year)
else:
print("%s is a leap year!" %year)
else:
print("%s is not a leap year :(" %year)
else:
print("%s is a leap year!" %year)
|
balance = 2222
annualInterestrate = 1.2
monthlyInterestrate = annualInterestrate/12.0
monthlyBalance = balance/12+monthlyInterestrate
while balance > 0:
return monthlyBalance ('Month: ' + str(month))
month += 1
print ('Minimum monthly payment: ' + str(monthlyPayment))
monthlyPayment = updatedBalance*monthlyInterestrate
print ('Remaining balance: ' + str(updatedBalance))
updatedBalance = updatedBalance-monthlyPayment
else:
print ('Total Paid: ' + str(monthlyPayment*12))
print ('Remaining blance: ' + str(updatedBalance))
|
from tkinter import *
from tkinter import messagebox
from PIL import ImageTk,Image
root = Tk()
root.title("Message Boxes")
root.iconbitmap("images/6/catICO.ico")
# showinfo, showerror, showwarning, askquestion, askokcancel, askyesno,
def popup():
response = messagebox.askyesno("This is the heading", "This is the body")
if response == 1:
myLabel = Label(root, text="You Clicked Yes!").pack()
else:
myLabel = Label(root, text="You Clicked No!").pack()
myButton = Button(root, text="Popup", command= lambda :popup()).pack()
root.mainloop()
|
# you can write to stdout for debugging purposes, e.g.
# print "this is a debug message"
def solution(X, A):
river = {}
i = 0
while len(river) < X and i<len(A):
if A[i] in river:
pass
else:
river[A[i]] = True
i += 1
if len(river)==X:
return i
else:
return -1
print('solution is'+str(solution(4,[1,1,1,1,1,1,1])))
|
def solution(S):
# write your code in Python 2.7
map={'}':'{',']':'[',')':'('}
stack=[]
for item in S:
if item in '[({':
stack.append(item)
elif len(stack)>=1 and stack[-1]==map[item]:
stack.pop()
else:
return 0
if len(stack)==0:
return 1
else:
return 0
|
#!/usr/bin/python3
import numpy as np
dataset=[11,10,12,14,15,13,15,102,12,14,107,10,10,13,12,14,108,12,11,12,15,15,11,10,12,14,15,13,15,14,12,13,20,12,25]
# Formula z= (Observations - Mean)/Standard Deviation
outliers=[]
def detect_outliers(data):
threshold = 3 #Within 3rd SD it is not an outlier
mean = np.mean(data)
std=np.std(data)
for i in data:
z_score = (i - mean) / std
if np.abs(z_score) > threshold:
outliers.append(i)
return outliers
O=detect_outliers(dataset)
print(O)
|
import unittest
from unittests_testing.calc_ import Calc
class TestRoot(unittest.TestCase):
"""
Testing square root of any number in calculator
"""
def setUp(self) -> None:
print('setUp')
def test_Sqrt_DataInputs(self):
print('test_Sqrt_DataInputs')
self.assertIsInstance(Calc.root(4), float)
self.assertIsInstance(Calc.root(9.0), float)
def test_Sqrt_Computing(self):
print('test_Sqrt_Computing')
self.assertEqual(Calc.root(0.0), 0)
self.assertEqual(Calc.root(625), 25.0)
self.assertEqual(Calc.root(4.0), 2.0)
def test_Sqrt_RaiseExceptions(self):
print('test_Sqrt_RaiseExceptions')
# self.assertRaises(ValueError, Calc.root, -25)
with self.assertRaises(ValueError):
Calc.root(-25)
# self.assertRaises(TypeError, Calc.root, "4")
with self.assertRaises(TypeError):
Calc.root("25")
def tearDown(self) -> None:
print('tearDown\n')
if __name__ == '__main__':
unittest.main()
|
from utils import *
import sys
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
class Ex1Multi:
def __init__(self):
self.data = None # DataFrame from original data
self.X = None # X matrix
self.y = None # y vector
self.m = None # Number of training examples
self.mu = None # Features' mean values
self.sigma = None # Features' std dev values
self.theta = None # Fitting parameters vector
self.num_iters = None # Number of iterations
self.alpha = None # Alpha parameter
self.J_history = None # Cost function history
def run(self):
self.load_and_normalize()
self.gradient_descent()
self.normal_equations()
@print_name
# @pause_after
def load_and_normalize(self):
print("Load data ...")
self.data = pd.read_csv("ex1multi-data/ex1data2.txt", header=None)
self.X = self.data.iloc[:, :-1] # All but last column to X
self.y = self.data.iloc[:, -1] # Last column to y
self.m = len(self.data)
print("First 10 examples from the dataset:")
[print("x = [{} {}], y = {}".format(*row)) for i, row in self.data.head(10).iterrows()]
self.X, self.mu, self.sigma = self.feature_normalization(self.X)
# Add intercept term
ones = np.ones([self.m, 1])
self.X = np.hstack([ones, self.X])
def feature_normalization(self, X):
mu = np.mean(X)
sigma = np.std(X)
X_norm = (X - mu) / sigma
return X_norm, mu, sigma
@print_name
# @pause_after
def gradient_descent(self):
self.alpha = 0.03
self.num_iters = 400
self.theta = np.zeros([3, 1])
self.y = self.y[:, np.newaxis]
self.theta, self.J_history = self.gradient_descent_multi(self.X, self.y, self.theta, self.alpha, self.num_iters)
self.plot_convergence(self.J_history)
print("Theta computed from gradient descent:")
print("[{:.2f} {:.2f} {:.2f}]".format(*np.squeeze(self.theta)))
# Estimate the price of a 1650 sq-ft, 3 br house
A = [1, 1650, 3]
for i in range(1, len(A)):
A[i] = (A[i] - self.mu[i - 1]) / self.sigma[i - 1]
price = np.dot(self.theta.T, A)
print("Predicted price of a 1650 sq-ft, 3 br house using gradient descent:")
print("{:.2f}".format(price[0]))
def gradient_descent_multi(self, X, y, theta, alpha, num_iters):
m = len(self.y)
n = len(theta)
J_history = np.zeros([num_iters, 1])
for i in range(num_iters):
err = np.dot(X, theta) - y
theta_new = theta - alpha/m * np.dot(X.T, err)
theta = theta_new
J_history[i] = self.compute_cost_multi(X, y, theta)
return theta, J_history
def compute_cost_multi(self, X, y, theta):
m = len(y)
return np.sum((np.dot(X, theta) - y)**2) / (2*m)
def plot_convergence(self, J_history):
fig, ax = plt.subplots()
ax.plot(np.arange(1, len(J_history) + 1), J_history, '-b', linewidth=2)
ax.set_xlabel("Number of iterations")
ax.set_ylabel("Cost J")
fig.savefig("ex1multi-data/convergence.png")
@print_name
def normal_equations(self):
self.X = self.data.iloc[:, :-1] # Reverse normalization
# Add intercept term
ones = np.ones([self.m, 1])
self.X = np.hstack([ones, self.X])
self.theta = self.normal_eqn(self.X, self.y)
print("Theta computed from the normal equations:")
print("[{:.2f} {:.2f} {:.2f}]".format(*np.squeeze(self.theta)))
price = self.theta.T @ [1, 1650, 3]
print("Predicted price of a 1650 sq-ft, 3 br house using normal equations:")
print("{:.2f}".format(price[0]))
def normal_eqn(self, X, y):
theta = np.linalg.inv(X.T @ X) @ X.T @ y # @ instead of np.dot()
return theta
if __name__ == '__main__':
ex1multi = Ex1Multi()
sys.exit(ex1multi.run())
|
"""
Define to_alternating_case(char*) such that each lowercase letter becomes uppercase and each
uppercase letter becomes lowercase.
https://www.codewars.com/kata/alternating-case-%3C-equals-%3E-alternating-case/train/python
"""
def to_alternating_case(s):
alt = ''
for c in s:
if c == c.lower():
alt += c.upper()
else:
alt += c.lower()
return alt
|
def func_or(a, b):
if get_val(a, b) > 0:
return True
return False
def func_xor(a, b):
if get_val(a, b) == 1:
return True
return False
def get_val(a, b):
return check_let(a) + check_let(b)
def check_let(x):
if type(x) == int and x != 0:
return 1
if x:
return 1
else:
return 0
|
def replace_exclamation(s):
vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
for vowel in vowels:
s = s.replace(vowel, "!")
return s
|
def evil(n):
bins = find_bin(n)
if sum(bins) % 2 == 0:
return "It's Evil!"
else:
return "It's Odious!"
def find_bin(n):
bins = []
while n >= 1:
rem = n % 2
n = n // 2
bins.append(rem)
return bins
|
def permutations(s):
# only one permutation of single char string
if len(s) <= 1:
return [s]
perms = []
# get pivot char
for i, c in enumerate(s):
perms.append([c])
# get remaining chars
remains = []
for j, x in enumerate(s):
if i != j:
remains.append(x)
# get permutations of remaining chars
z = permutations(remains)
# concat permutations of remaining chars to pivot char
for t in z:
perms.append([c] + t)
# remove duplicates
results = []
for word in perms:
if word not in results:
results.append(word)
return results
|
class Matrix(object):
def __init__(self, arr):
self.arr = arr
self.shape = (len(arr), len(arr[0]))
def __add__(self, other):
if self.shape != other.shape:
return "Matrices must have same shape."
new_mat = []
for i, row in enumerate(self.arr):
tmp_row = []
for j, n in enumerate(row):
tmp_row.append(n + other.arr[i][j])
new_mat.append(tmp_row)
return Matrix(new_mat)
def __mul__(self, other):
if self.shape[1] != other.shape[0]:
return "Matrix shapes not compatible with multiplicaton."
new_mat = []
for i, row in enumerate(self.arr):
tmp_row = []
for k in range(self.shape[0]):
tmp_row.append(sum([self.arr[i][j] * other.arr[j][k]
for j in range(self.shape[1])]))
new_mat.append(tmp_row)
return Matrix(new_mat)
def trace(self):
if self.shape[0] != self.shape[1]:
return "Method requries a square matrix."
total = 0
for i in range(self.shape[0]):
total += self.arr[i][i]
return total
|
from math import log
def count_trailing_zeros(num):
zeros = 0
for n in xrange(0, num + 1, 5):
if n == 0:
continue
for m in xrange(1, int(log(n, 5) + 1)):
if n % (5 ** m) == 0:
zeros += 1
return zeros
|
from datetime import date
def days_until_christmas(day):
year = day.year
if day >= date(year, 12, 26):
year += 1
return (date(year, 12, 25) - day).days
|
def string_chunk(string, *args):
if len(args) == 0 or args[0] <= 0 or type(args[0]) != int:
return []
return [string[x:x + args[0]] for x in xrange(0, len(string), args[0])]
|
import pandas as pd
import numpy as np
## Cleaning Economical Dataframe
#The Index of economic freedom dataset comes in 5 years [ 2013,2014,2015,2016,2017 ]. The structure of the dataset in 2017 is different from the structure of those in the previous years.
#The function below matches all the years' structures and the countries names to be identical to that present in the Panama Papers.
def cleaning_index_data(df,year):
## Input:
# df : dataframe
# year : a string called year used to filter columns.
## Output:
# df : cleaned dataframe
# Variables needed to manipulate through the data.
int_year = int(year) + 1
string_year = str(int_year)
score = string_year + ' Score'
# Changing those columns from objects to float
change_type_columns = ['Public Debt (% of GDP)','FDI Inflow (Millions)','Inflation (%)',\
'Unemployment (%)','GDP per Capita (PPP)','5 Year GDP Growth Rate (%)',\
'GDP Growth Rate (%)','GDP (Billions, PPP)','Gov\'t Expenditure % of GDP ',\
'Tax Burden % of GDP','Corporate Tax Rate (%)','Income Tax Rate (%)','Tariff Rate (%)',\
'Judical Effectiveness','Property Rights','Government Integrity']
# Fix the country name to match that in Panama papers.
if (int_year == 2013):
# Extract the indexes of the dataframe to a list.
as_list = df.index.tolist()
# Get the index number of the country needed.
idx = as_list.index('Bahamas, The')
# Change country name to the one desired.
as_list[idx] = 'Bahamas'
# Make the new list the index of the dataframe.
df.index = as_list
# Fix the country name to match that in Panama papers.
if (int_year != 2013):
# Extract the indexes of the dataframe to a list.
as_list = df.index.tolist()
# Get the index number of the country needed.
idx = as_list.index('Hong Kong SAR')
# Change country name to the one desired.
as_list[idx] = 'Hong Kong'
# Make the new list the index of the dataframe.
df.index = as_list
# Cleaning the dataframe of 2017.
if(int_year == 2017):
# Columns to get rid of.
columns = ['CountryID','WEBNAME','Country']
# change the column name score to Score to match others.
df = df.rename(columns={score:'Score'})
# Drop the columns we don't need.
df = df.drop(columns,axis=1)
# Change object type to float and fill with 0 where there is full strings.
df[change_type_columns] = df[change_type_columns].apply(pd.to_numeric, errors='coerce')
df = df.fillna(0)
return df
# Cleaning all the other dataframe years.
# Renaming the columns
df = df.rename(columns={score:'Score','Fiscal Freedom ':'Tax Burden', 'Freedom from Corruption':'Government Integrity'})
# Columns to get rid of.
column_name_1 = 'Change in Yearly Score from ' + year
column_name_2 = 'Change in Property Rights from ' + year
column_name_3 = 'Change in Freedom from Corruption from ' + year
column_name_4 = 'Change in Fiscal Freedom from ' + year
column_name_5 = 'Change in Gov\'t Spending from ' + year
column_name_6 = 'Change in Business Freedom from ' + year
column_name_7 = 'Change in Labor Freedom from ' + year
column_name_8 = 'Change in Monetary Freedom from ' + year
column_name_9 = 'Change in Trade Freedom from ' + year
column_name_10 = 'Change in Investment Freedom from ' + year
column_name_11 = 'Change in Financial Freedom from ' + year
# Putting the columns in an array
columns = ['CountryID','WEBNAME','Country',column_name_1,column_name_2,column_name_3,\
column_name_4,column_name_5,column_name_6,\
column_name_7,column_name_8,column_name_9,column_name_10,column_name_11]
# Removing Judical Effectiveness as it was only included in 2017.
change_type_columns.remove('Judical Effectiveness')
# Change object type to float and fill with 0 where there is full strings.
df[change_type_columns] = df[change_type_columns].apply(pd.to_numeric, errors='coerce')
df = df.drop(columns,axis=1)
df = df.fillna(0)
return df
|
print("Your top ten spirit animals are: ")
import random
adjectives = ["adventurous",
"excited",
"crazy",
"boudless",
"brave",
"cheerful",
"dynamic",
"fun",
"energetic",
"amused"]
colors = ["red",
"orange",
"yellow",
"green",
"blue",
"purple",
"pink",
"brown",
"black",
"white"]
animals = ["dog",
"ant",
"cat",
"monkey",
"tiger",
"cheetah",
"giraffe",
"dolphin",
"lion",
"elephant"]
for i in range(10):
animals_length = len(animals)
colors_length = len(colors)
adjectives_length = len(adjectives)
random_index = random.randint(0,adjectives_length-1)
random_index_2 = random.randint(0,colors_length-1)
random_index_3 = random.randint(0,animals_length-1)
print(adjectives[random_index] + " " + colors[random_index_2] + " " + animals[random_index_3])
|
#
# @lc app=leetcode id=101 lang=python3
#
# [101] Symmetric Tree
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def dfs(self, l: TreeNode, r: TreeNode) -> bool:
if not l and not r:
return True
elif not l:
return False
elif not r:
return False
if l.val != r.val:
return False
return self.dfs(l.right, r.left) and self.dfs(l.left, r.right)
# def isSymmetric(self, root: TreeNode) -> bool:
# """ Strategy 1: DFS
# Runtime: O(n), where n is the # of nodes
# Space: O(1)
# Args:
# root (TreeNode): the root of the node
# Returns:
# bool: determine whether the tree is symmetric around the center.
# """
# if not root:
# return True
# return self.dfs(root.left, root.right)
def isSymmetric(self, root: TreeNode) -> bool:
""" Strategy 1: Iterative
Runtime: O(n), where n is the # of nodes
Space: O(1)
Args:
root (TreeNode): the root of the node
Returns:
bool: determine whether the tree is symmetric around the center.
"""
if not root:
return True
q_l = [root]
q_r = [root]
while q_l and q_r:
node_l = q_l.pop(0)
node_r = q_r.pop(0)
if not node_l and not node_r:
continue
if not node_l or not node_r:
return False
if node_l.val != node_r.val:
return False
for child in [node_l.left, node_l.right]:
q_l.append(child)
for child in [node_r.right, node_r.left]:
q_r.append(child)
return True
# @lc code=end
|
#
# @lc app=leetcode id=110 lang=python3
#
# [110] Balanced Binary Tree
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def dfs(self, node: TreeNode) -> (bool, int):
if not node:
return True, 0
left, left_height = self.dfs(node.left)
if not left:
return False, left_height
right, right_height = self.dfs(node.right)
if not right:
return False, right_height
return (abs(left_height - right_height) < 2, 1 + max(left_height, right_height))
def isBalanced(self, root: TreeNode) -> bool:
""" DFS
Runtime: O(n), where n is the number of nodes in the tree
Space: O(n)
Args:
root (TreeNode): the root of the node
Returns:
bool: determine where the tree is height-balanced
"""
return self.dfs(root)[0]
# @lc code=end
|
#
# @lc app=leetcode id=5 lang=python3
#
# [5] Longest Palindromic Substring
#
# @lc code=start
class Solution:
def longestPalindrome(self, s: str) -> str:
"""Strategy 1: Dynamic Programming
Args:
s (str): The length of the string
Returns:
str: the longest palindrome
a b c
a 1
b 1
c 1
"""
n = len(s)
dp = [[True if y == x else False for x in range(n)] for y in range(n)]
# dp = [[False] * n for _ in range(n)]
# dp[0][0] = True
longest = 1
start = 0
for x in range(1, n):
for y in range(x):
if s[y] == s[x] and (x == y + 1 or dp[y+1][x-1]):
dp[y][x] = True
if longest < x - y + 1:
longest = x - y + 1
start = y
return s[start: start + longest]
# @lc code=end
|
#
# @lc app=leetcode id=1299 lang=python3
#
# [1299] Replace Elements with Greatest Element on Right Side
#
# @lc code=start
class Solution:
def replaceElements(self, arr: List[int]) -> List[int]:
""" Strategey 1: One pass
Runtime: O(n), where n is the size of arr
Space:O(1)
Args:
arr (List[int]): list of integers
Returns:
List[int]: the modified arr, where every element is the greatest
element to the right of the original array.
"""
n = len(arr)
curr = 0
maxR = arr[-1]
for i in range(n-2, -1, -1):
curr = arr[i]
arr[i] = maxR
maxR = max(maxR, curr)
arr[n-1] = -1
return arr
# @lc code=end
|
#
# @lc app=leetcode id=144 lang=python3
#
# [144] Binary Tree Preorder Traversal
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from typing import List
class Solution:
# def preorderTraversal(self, root: TreeNode) -> List[int]:
# """ Stragtegy 1: Iterative
# Runtime: O(n), where n is the number of nodes
# Space:O(n)
# Args:
# root (TreeNode): the root of the tree.
# Returns:
# List[int]: a list of nodes in preorder.
# """
# if not root:
# return []
# stack = [root]
# output = []
# while stack:
# node = stack.pop()
# output.append(node.val)
# if node.right:
# stack.append(node.right)
# if node.left:
# stack.append(node.left)
# return output
def preorderTraversal(self, root: TreeNode) -> List[int]:
""" Stragtegy 1: Iterative
Runtime: O(n), where n is the number of nodes
Space:O(n)
Args:
root (TreeNode): the root of the tree.
Returns:
List[int]: a list of nodes in preorder.
"""
if not root:
return []
output = [root.val]
output += self.preorderTraversal(root.left)
output += self.preorderTraversal(root.right)
return output
# @lc code=end
|
#
# @lc app=leetcode id=55 lang=python3
#
# [55] Jump Game
#
from typing import List
# @lc code=start
class Solution:
# def canJump(self, nums: List[int]) -> bool:
# """ Strategey 1: Backward + DP/Greedy
# Runtime: O(n), where n is # of integers in nums
# Space:(1)
# Args:
# nums (List[int]): list of non-negative integers
# Returns:
# bool: determine whether you can jump from index 0 to index n -1
# """
# n = len(nums)
# target = n-1
# if nums[0] > target:
# return True
# for i in range(target-1, -1, -1):
# if nums[i] + i >= target:
# target = i
# return target == 0
def canJump(self, nums: List[int]) -> bool:
""" Strategey 1: Forward + DP/Greedy
Runtime: O(n), where n is # of integers in nums
Space:(1)
Args:
nums (List[int]): list of non-negative integers
Returns:
bool: determine whether you can jump from index 0 to index n -1
"""
n = len(nums)
maxPos = nums[0]
for i in range(1, n):
if maxPos < i:
return False
maxPos = max(maxPos, nums[i] + i)
return True
# @lc code=end
|
#
# @lc app=leetcode id=23 lang=python3
#
# [23] Merge k Sorted Lists
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
import heapq
from typing import List
class Solution:
import heapq
ListNode.__lt__ = lambda self, other: self.val < other.val
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
""" Streategy 1: Priority Queue
RunTime: O(N log k)
Space: O(k)
Args:
lists (List[ListNode]): list of linked lists
Returns:
ListNode: the merged linked lists
"""
if not lists:
return None
heap = []
merged = curr = ListNode(-1)
for l in lists:
if l:
heapq.heappush(heap, (l.val, l))
while heap:
_, node = heapq.heappop(heap)
curr.next = node
curr = curr.next
node = node.next
if node:
heapq.heappush(heap, (node.val, node))
return merged.next
# @lc code=end
|
#
# @lc app=leetcode id=897 lang=python3
#
# [897] Increasing Order Search Tree
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def increasingBST(self, root: TreeNode) -> TreeNode:
"""Strategy 1: In order traversal
Runtime: O(n)
Space: O(h), where h is the height of the tree
Args:
root (TreeNode): the root of the tree
Returns:
TreeNode: Return an in order tree with
"""
if not root:
return
output = curr = TreeNode(-1)
def inOrder(node: TreeNode) -> None:
nonlocal curr
if not node:
return
inOrder(node.left)
curr.right = node
node.left = None
curr = curr.right
inOrder(node.right)
inOrder(root)
return output.right
# @lc code=end
|
#
# @lc app=leetcode id=49 lang=python3
#
# [49] Group Anagrams
#
# @lc code=start
from collections import defaultdict
class Solution:
from collections import defaultdict
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
"""Strategy 1: Hash + Array
Runtime: O(n K), where n is the number of words in strs, k is the length of the longest word
Space: O(n k)
Args:
strs (List[str]): A list of words
Returns:
List[List[str]]: list of grouped anagrams
"""
anagrams = defaultdict(list)
for word in strs:
alphabet_count = [0] * 26
for c in word:
alphabet_count[ord(c) - ord('a')] += 1
anagrams[tuple(alphabet_count)].append(word)
return anagrams.values()
# @lc code=end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.