text stringlengths 37 1.41M |
|---|
def leitura():
n = int(input("n: "))
lista = []
for i in range(n):
num = int(input("Insira um número inteiro: "))
lista.append(num)
print(lista)
if __name__ == '__main__':
leitura()
|
def f_direita(direcao):
direcao = direcao + 1
if direcao == 4:
direcao = 0
return direcao
def f_esquerda(direcao):
direcao = direcao - 1
if direcao == -1:
direcao = 3
return direcao
def main():
l = ["Norte", "Leste", "Sul", "Oeste"]
l1 = ["D", "D", "D", "D", "E", "D",... |
def maior(lista):
m = 0
for j in lista:
if j > m:
m = j
return m
def posicao_do_max():
lista = [1, 2, 3, 4, 5, 6, 7, 8, 9, 3, 4, 2, 7]
print(lista)
ma = maior(lista)
for i in lista:
if i == ma:
indice = lista.index(i)
print(f"O maior indi... |
# Define a list of names
names = ["kamal", "Ron", "karan", "Ginney"]
print(names)
names.append("Anuj")
names.sort()
print(names) |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def sortedListToBST(self, head):
"""
:type... |
"""Quick Sort"""
def q_sort(array):
"""Return sorted array."""
if not array:
return None
if len(array) == 1 or max(array) == min(array):
return array
pivot = array[len(array) // 2]
print pivot
left = list()
right = list()
for elem in array:
if elem <= pivot:
... |
import unittest
def product_others(A):
if len(A) < 2:
return "There are no other elements in the array."
product = 1
result = list([])
result.append(product)
for i in range(len(A) - 1):
product *= A[i]
result.append(product)
product = 1
for i in range(len(A) - 1, 0, -1):
product *= A[i]
result[i - 1] ... |
# swap bits at positons i and j in x
def swap_bits(x, i, j):
i_bit = (x >> i) & 1
j_bit = (x >> j) & 1
if i_bit != j_bit:
x ^= (1 << i) | (1 << j)
return x
print swap_bits(5, 1, 2) |
import unittest
def max_profit(S):
if len(S) < 2:
raise IndexError('Geting a profit requires at least 2 prices')
buy = S[0]
sell = S[1]
profit = sell - buy
lowest = min(buy, sell)
for stock in S[1:]:
profit = max(stock - lowest, profit)
lowest = min(stock, lowest)
return profit
class MaxProfitTester(unit... |
import unittest
def reverse_string(S):
start = 0
end = len(S) - 1
st_list = list(S)
while start != end and start != end + 1:
st_list[start], st_list[end] = st_list[end], st_list[start]
end -= 1
start += 1
return ''.join(st_list)
class ReverseStringTester(unittest.TestCase):... |
# The Yes
# You are building a social travel app.
# You are given two strings:
# 1 string of the current user’s wishlist
# 1 string of other users wishlists
# Write a function that returns a list of potential travel buddies sorted by number of matches.
# Current user wishlist:
# “Amsterdam,Barcelona,London,Prague”
#... |
# LISTS (25pts)
# Show work on all problems. Manually finding the answer doesn't count
# PROBLEM 1 (Using List Comprehensions - 8pts)
# Use list comprehensions to do the following:
# a) Make a list of numbers from 1 to 100
my_list1 = [x for x in range(1, 101)]
print(my_list1)
# b) Make a list of even numbers from 20... |
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def get_depth(self, A):
if A is None:
return 0
else:
return max(1 + self.get_depth(A.left), 1 + self.get_depth(A.right))... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param A : list of linked list
# @return the head node in the linked list
def mergeKLists(self, A):
arr = []
counter = 0
while coun... |
from urllib.request import urlopen
import pandas as pd
import numpy as np
class getXsections:
"""getXsections
Downloads cross section information from https://clas.sinp.msu.ru/cgi-bin/jlab/db.cgi and parses into dataframes
Only tested for getting cross sections currently. Not fulling working API for the... |
#!/usr/bin/env python
# encoding: utf-8
"""
populationcode.py
Created by Loic Matthey on 2011-05-30.
Copyright (c) 2011 Gatsby Unit. All rights reserved.
"""
import numpy as np
import pylab as plt
class PopulationCode:
def __init__(self, N):
self.N = N
class PopulationCodeAngle(PopulationCode):
... |
import numpy as np
# Create a function to fit the data to a Gaussian given some initial values
def gaussian(x,mu,sigm,amp):
'''
Gaussian distribution
x - values for the fit
p[0]: mu - mean of the distribution
p[1]: sigma - stddev
p[2]: amplitude
'''
return amp*np.exp(-(x-mu)**2/(2*... |
#This program is designed such that it takes todays date and display the temperatures of all days of the month making 2 categories. Days which are already passed and future days.
from bs4 import BeautifulSoup
import urllib
import datetime
now = datetime.datetime.now()
weatherURL = "http://www.wunderground.com/history... |
"""
- A Dictionary is a collection which is unordered, changeable, and indexed
- Dictionaries allow no duplicate members
"""
# Creating a Dictionary #
person = {
'firstName': 'Andrew',
'lastName': 'Cavallaro',
'age': 29
}
# Creating a Dictionary using a constructor #
anotherPerson = dict(firstName... |
products = [] # 建立一個清單
while True:
name = input('請輸入商品名稱: ')
if name == 'q': # quit 離開
break
price = input('請輸入商品價格: ')
# price 是字串,因為('請輸入商品價格: ')是字串
price = int(price)
# 把字串price 轉換成 int 數字
# 往下的price, 所有提到price 價格的部份,就是數字
products.append([name, price])
print(products)
print('----------------------', '... |
#!/usr/bin/env python
# coding: utf-8
# In[73]:
import pandas as pd
# In[74]:
data=pd.read_csv("Iris.csv")
# In[75]:
# 150 observations
# 4 features - sepal length, sepal width, petal length, petal width
# Response variable is the iris species
# Classification problem since response is categorical
# In[7... |
###############################VECTOR MATH######################################
class Vector(object):
def __init__(self,x=0.0,y=0.0):
self.x=x
self.y=y
def __str__(self):
return "(%s,%s)"%(self.x,self.y)
@staticmethod
def from_points(p1,p2):
return Vector(p2[0]-p1[0],p2[... |
"""
The decimal number, 585 = 1001001001 (binary), is palindromic in both bases.
Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.
(Please note that the palindromic number, in either base, may not include leading zeros.)
"""
def isDoublePalindrome(n, k):
bits = []
... |
"""
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
"""
import math
def sieveofSundaram(n):
nums = list(range(2, n + 1))
for i in range(2, n - 1, 2):
nums[i] = 0
for i in range(1, int((-1 + math.sqrt(n)) / 2) + 1):
j = i
whi... |
"""
The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.
Find the sum of the only eleven primes that are both truncatable fr... |
def integerdigits(integer):
total = 0
while integer:
total += (integer % 10)
integer /= 10
return total
def powerdigit(power, powertodigits):
if power not in powertodigits:
powertodigits[power] = integerdigits(2**power)
return powertodigits[power]
def main():
powerdig... |
import math # 엔트로피 계산에 로그함수를 쓰기 위해 math 모듈을 불러온다.
import collections
from collections import defaultdict
def getInputs():
dataSet = [['M', '30', 'NO', 'YES', 'NO', 'NO'],
['F', '20', 'YES', 'YES', 'YES', 'NO'],
['F', '20', 'YES', 'YES', 'NO', 'NO'],
['F', ... |
#辅助函数——交换两个数
def exchange(a,i,j):
temp = a[i]
a[i] = a[j]
a[j] = temp
#下沉函数
def sink(a,k,N):
while 2*k < N:
#选出两个子结点中大的那个
j = 2 * k
if j<N and a[j]<a[j+1]: #j<N是为了保证j+1<=N
j += 1
#如果结点k不比两个子节点小,说明下沉结束
if not a[k]<a[j]:
break
#下沉
... |
class flowGraph:
"""
Represents a flow graph for assembly source code
"""
def __init__(self, blocks):
"""
Initialises some variables and calls the methods for building the graph.
"""
self.dotSource = ""
self.basicBlocks = blocks
self.buildGraph()
... |
# Uses python3
import sys
def gcd_naive(a, b):
temp = 1
while temp != 0:
temp = a % b
a = b
b = temp
return a
def lcm_naive(a, b):
if min(a,b)==0:
return 0
return (a * b) // gcd_naive(a, b)
if __name__ == '__main__':
input = sys.stdin.read()
a, b = map(i... |
# python3
class Heap(object):
def __init__(self, arr):
self.size = len(arr)
self.sort_size = self.size
self.swaps = []
self.heap = arr
for i in range(self.size, -1, -1):
self.sift_down(i)
self.sorted_heap = []
def parent(self, i):
return (i - ... |
def binary_to_dec(num_str):
n = len(num_str)
num = 0
for i in range(n):
num += int(num_str[i]) * (2 ** i)
return num
def merge(a, b, total_inversions):
i, j = 0, 0
m, n = len(a), len(b)
c = [0] * (m + n)
k = 0
while i < m and j < n:
if a[i] <= b[j]:
c[k... |
# Uses python3
def calc_fib(n):
if (n <= 1):
return n
else:
fibs = [0]*(n+1)
fibs[0] = 0
fibs[1] = 1
for i in range(2,n+1):
fibs[i] = fibs[i-1] + fibs[i-2]
return fibs[n]
n = int(input())
print(calc_fib(n))
|
# Uses python3
import sys
# def get_point_count(point, segments, left, right):
# if left > right:
# return point
# value, count = point
# mid = int(left + (right - left) / 2)
# start, end = segments[mid]
# if value >= start and value <= end:
# count += 1
# # if value > start:
#... |
""" Creates an Item object that will have instances that functions as
items throughout the game. The Item object will be used for player
inventory and the shop object. Items need properties for type, name,
tier, and stats. An item's name needs to be able to be adjusted based
on its name and type."""
cla... |
n = int(input())
num_list = list(map(int, input().split()))
min = num_list[0]
for num in num_list:
if min > num:
min = num
print(min)
|
num = int(input())
local = num * 5
luogu = 11 + num * 3
if local < luogu:
print("Local")
else:
print("Luogu")
|
import math
m, h = map(float, input().split())
BMI = m / (h ** 2)
if BMI < 18.5:
print("Underweight")
elif BMI >= 18.5 and BMI < 24:
print("Normal")
else:
BMI = format(BMI, ".4f")
B = str(BMI).strip("0")[:7]
if B[len(B) - 1] == ".":
B = B + "0"
print(B)
print("Overweight") |
import math
num = int(input())
money = 0
i = 0
while i < 3:
pen, price = map(int, input().split())
if i == 0:
money = math.ceil(num / pen) * price
else:
if money > math.ceil(num / pen) * price:
money = math.ceil(num / pen) * price
i += 1
print(money) |
# isspace 判断空白字符,只包含空白字符(\n \r \t)则会返回True
space_str = " "
print(space_str.isspace())
# 判断字符串中是否只包含数字
# 三个方法都不能判断小数
num_str = "1"
print(num_str.isdecimal())
print(num_str.isdigit()) # 可以判断特殊数字,比如unicode
print(num_str.isnumeric()) # 可以判断汉字数字,比如一千零一 |
test_list = ["zhangsan", "lisi", "wagnwu"]
# index方法 返回元素第一次出现的下标,没有则会报错
print(test_list.index("lisi"))
# append方法 末尾追加
test_list.append("haha")
# insert方法 在指定位置插入
test_list.insert(1, "haohao")
# extend方法 合并列表
temp_list = ["孙悟空", "二师兄"]
test_list.extend(temp_list)
# remove方法 删除第一次出现的指定的数据
test_list.remove("haohao"... |
import numpy as np
import random
from matplotlib import pyplot as plt
from sklearn.metrics import accuracy_score
def sigmoid(z):
'''
Sigmoid function on a vector this is included for use as your activation function
Input: a vector of elements to preform sigmoid on
Output: a vector ... |
num1 =int (input('enter the first number'))
num2 =int (input('enter the second number'))
add = num1 +num2
diff =num1-num2
mul= num1*num2
div= num1/num2
floor_div =num1//num2
power=num1 ** num2
modulus= num1%num2
print('sum of ',num1, 'and',num2,' is:', add)
print('subtraction of ',num1,'and',num2,' is:', diff)
print('m... |
# —*— encoding=utf-8 —*—
import lemma
import nltk
class TianGaoSmooth():
''' This is a new approach for measuring similarity between two texts. It is also a new text classification method.
usage:
>>>smoother = TianGaoSmooth(n_grams='the number you want')
>>>smoother.tiangao_smoothing(train_path='the p... |
f = open('input.txt')
seats = None
sum = 0
for l in f:
l = l.rstrip()
if l:
if seats == None:
seats = set(l)
else:
seats = seats.intersection(set(l))
else:
sum += len(seats)
seats = None
sum += len(seats)
print("Looks like %d" % sum) |
# จงแสดง "banana"
fruits = ["apple", "banana", "cherry"]
print(fruits[1])
print(fruits)
# จงแก้ไขข้อมูลจาก "apple" เป็น "kiwi"
fruits = ["apple", "banana", "cherry"]
fruits[0] = "kiwi"
print(fruits)
# จงเพิ่ม "kiwi" ไปยัง fruits list fruits = ["apple", "banana", "cherry"]
kiwiAdd = ["kiwi"]
fruitsAdded = fruits + kiw... |
#!usr/bin/env python3
"""
analyzes a text file containing an unknown number of integers,
returning minimum value, maximum value, median, total number
processed and the mode.
"""
# standard library imports
from collections import Counter
from collections import namedtuple
def find_median(lst):
"""
finds or ... |
def merge(left,right):
result=[]
i,j=0,0
while (i < len(left) and j < len(right)):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
while (i < len(left)):
result.append(left[i])
i +=... |
'''
9 回文数
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
你能不将整数转为字符串来解决这个问题吗?
'''
def isPalindrome(x):
if x < 0:
return False
elif x < 10 and x >= 0:
return True
else:
list1 = list()
while True:
if x // 10:
list1.append(x % 10)
x /... |
"""
二分法查找-简介
二分法查找,也称为折半法,是一种在有序数组中查找特定元素的搜索算法。
二分法查找的思路如下:
(1)首先,从数组的中间元素开始搜索,如果该元素正好是目标元素,则搜索过程结束,否则执行下一步。
(2)如果目标元素大于/小于中间元素,则在数组大于/小于中间元素的那一半区域查找,然后重复步骤(1)的操作。
(3)如果某一步数组为空,则表示找不到目标元素。
二分法查找的时间复杂度O(logn)。
"""
"""
二分法查找的前提条件:从有序数组[列表]中进行查找
"""
"""
需求:
二分法查找指定数值key在数组(列表)中的索引位置,如果未找到,返回None
"""
# 数组为升序
def b... |
from common import *
depth = 150
win = False
side = 'a'
def best_first():
initial_state = (3, 3, 'a')
frontier_states = list()
frontier_states.append(initial_state)
iterate_over_states(frontier_states, 0)
print("Finished! Win: " + str(win))
def iterate_over_states(frontier_states, current_depth... |
# fermat
import sys
def isqrt(n):
x = n
y = (x + 1) // 2
while y < x:
x = y
y = (x + n//x) // 2
return x
def is_square(n):
if not n % 48 in (0,1,4,9,16,25,33,36):
return False
x = isqrt(n)
return x*x == n
def fermat(n):
a = isqrt(n)
b2 = a*a - n
while no... |
lemb = dict()
lemb['nome'] = str(input(f'Digite seu nome: '))
for v, n in lemb.items():
print(f' O {v} é {n}')
|
print('\033[1;32m~'*30)
print('BANCO DE DADOS ')
print('~'*30)
amigos = 0
man = 0
totalman = 0
mulher = 0
while True:
Amigos = str(input('\nAmigos: '))
amigos += 1
idade = int(input('\nIdade: '))
sexo = ' '
continuar = ' '
while sexo not in 'MF':
sexo = str(input('\nSexo: [M/F] ')).s... |
def initcity(city,country,population=""):
city = city.title().strip()
country = country.title().strip()
if population:
return city + ", " + country + " - population " + str(population)
else:
return city + ", " + country |
#LINEAR REGRESSION WITH ONE VARIABLE
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def calculate_cost(x, y, theta, m):
cost = np.asscalar((1/(2*m)) * ((np.dot(x,theta)-y)**2).sum())
return cost
def Gradient_Descent(x, y, theta):
global cost_values
m = x.shape[0]
iterations... |
import random
class TrackingSystem(object):
''' Defines the tracking system interface. '''
_initialised = False
def retrieve(self, map, drone):
''' Retrieves the location of a drone on a map. '''
if not self._initialised:
self._initialised = True
rando... |
def isPrime(n):
n=abs(n)
if n==1 or n==0:
return False
if n==2:
return True
if (n%2 == 0):
return False
for x in range(3,int(n**0.5+1),2):
if n%x==0:
return False
else:
return True
def getLcm(a, b):
lcm = 1
# ... |
#coding:utf-8
import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
def __init__(self,all_settings,screen,ship):
super().__init__()
self.screen=screen
self.rect=pygame.Rect(0,0,all_settings.bullet_width,
all_settings.bullet_height)
self.rect.centerx=ship.rect.centerx
self.rect.top=ship.... |
import pygame
import time
import random
# initialize the game
pygame.init()
# setting colours
white = (255, 255, 255)
red = (213, 50, 80)
black = (40, 40, 40)
blue = (50, 153, 213)
green = (0, 255, 0)
yellow = (255, 255, 102)
# initialising the game window
width, height = 800, 600
dis = pygame.display.set_mode((wi... |
#!/usr/bin/Python3
import random
from parameters import Parameters as p
class agent:
agent_x = 0 # agent X-coordinate
agent_y = 0 # agent Y-coordinate
ax_init = 0 # initial agent X-coordinate
ay_init = 0 # initial agent Y-coordinate
state_vector = [] # Contains state information which is the i... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Este programa toma el archivo passwd, lo lee linea a linea y luego imprime
# el primer campo de cada línea
# seudo código
#
# 1. Leer TODO el archivo passwd y guardar su contenido en passwdmem
# 2. Separar el contenido de passwdmem por líneas y guardar el resultado en pa... |
#Fungsi dengan return value
def kuadrat(argument):
total = argument**2
print('nilai kuadrat dari',argument,'adalah',total)
return total
kuadrat(3)
print(kuadrat(2))
i = kuadrat(4)
print(i)
print('-'*50)
#Fungsi dengan return value dan multiple argument
def penjumlahan(argument1,argument2):
... |
class Cities:
def __init__(self):
self._cities = ['Paris', 'Berlin', 'Rome', 'Madrid']
self._index = 0
def __len__(self):
return len(self._cities)
def __iter__(self):
return self.CityIterator(self)
def __getitem__(self, s):
return self._cities[s]
... |
squares = [i**2 for i in range(1, 101) if i%2]
print(squares)
import dis
compiled_code = compile('[i**2 for i in range(6)]',
filename='string', mode='eval')
dis.dis(compiled_code)
table2 = [[i+j for i in range(1, 11)] for j in range(1, 11)]
print(table2)
#pascals
from math import factori... |
#assigning value through slice
l = [1, 2, 3, 4, 5]
print(id(l))
l[0:3] = "python"
print(l, id(l))
l[2:5] = []
print(l, id(l))
#insertion
l[2:2] = "rosha"
print(l, id(l)) |
from itertools import count, cycle, repeat, islice
#count
g = count(10)
l = list(islice(g, 5))
print(l)
#range can only take integers
g = count(1, 0.5)
print(list(islice(g, 10)))
g = count((1+2j), (1+1j))
print(list(islice(g, 10)))
#cycle will work with both iterables and iterators
g = cycle(('red', 'green', 'blue')... |
#class instances are callable if you implement the
#__call__
#using the class as the decorator factory
class MyClass:
def __init__(self, a, b):
self.a = a
self.b = b
def __call__(self, fn):
from functools import wraps
print("Class initiated")
@wraps(fn)
d... |
def my_func(a, b, *args):
print(a,type(a))
print(b,type(b))
print(args,type(args))
my_func(1,2,'a',6,1,9,'r')
def my_func1(a,b,*args,d):
pass
my_func1(1,2,3,4)
def my_func3(a,b,c):
print(a,type(a))
print(b, type(b))
print(c, type(c))
l = [1,2,3,4]
my_func3(*l)
def avg(*args):
c... |
def counter(fn):
count = 0
def inner(*args, **kwargs):
nonlocal count
count += 1
print(count)
return fn(*args, **kwargs)
return inner
def mult(a, b, c=5):
"""testing decorators :)"""
return a * b * c
mult = counter(mult)
print(mult.__name__)
print(mult.__closure__... |
#!/usr/bin/env python
import sys
factorial = [1]
for i in range(1,10):
factorial.append(i*factorial[i-1])
def value(n):
if n == 0: return 1
sum_fact = 0
while n > 0:
d = n%10
sum_fact += factorial[d]
n //= 10
return sum_fact
def get_chain(n):
chain = [n]
while ... |
#!/usr/bin/env python3
import sys
import logging
from prime_numbers import is_prime,primes_less_than
primes = []
max_prime = -1
def setup_primes(n):
global primes
global max_prime
primes = primes_less_than(n)
max_prime = max(primes)
print("%d primes less than %d"%(len(primes),n))
def value(a,b... |
#!/usr/bin/env python
from itertools import product
from combinatorics import combinator
C = combinator([0,1,2,3,4,5,6,7,8,9],6)
confs = [tuple(c) for c in C]
squares = ["%02d"%(n**2) for n in range(1,10)]
digit_pairs = [(int(c[0]),int(c[1])) for c in squares]
def check(c1,c2):
testc1 = c1
testc2 = c2
... |
#!/usr/bin/env python
import sys
n_max = int(sys.argv[1])
f_max = int(sys.argv[2])
table = [1 for n in range(n_max+1)]
n = 1
while n <= n_max:
n += 1
for i in range(n,n_max+1):
table[i] += table[i-n]
table[i] %= f_max
if i == n:
print(i,table[i])
if table[i] =... |
#!/usr/bin/env python
def inverse(a,m):
t = 0
r = m
new_t = 1
new_r = a
while new_r != 0:
q = r//new_r
t,new_t = new_t,t - q*new_t
r,new_r = new_r,r - q*new_r
if r > 1:
return None
if t < 0:
t += m
return t
def power(... |
#!/usr/bin/env python
import sys
import prime_numbers
from utils import seq_string
def n_digits(n):
return len(str(n))
def rotation(s):
return s[1:] + s[0]
def gen_rot_set(s):
answer = [s]
for i in range(len(s)):
s = rotation(s)
if s not in answer:
answer.append(s)
r... |
#!/usr/bin/env python
import sys
def gen_combos(n,m):
if m == 1:
return [[n]]
answer = []
for i in range(1,n-m+2):
for sub in gen_combos(n-i,m-1):
answer.append([i]+sub[:])
return answer
existing_facts = [1]
def factorial(n):
if n > len(existing... |
#!/usr/bin/env python
import sys
def riffle(l):
k = len(l)//2
answer = []
for i in range(k):
answer.append(l[i])
answer.append(l[k+i])
return answer
def in_order(l):
for i in range(len(l)):
if l[i]-1 != i:
return False
return True
def print_deck(l):... |
#!/usr/bin/env python
def is_possible(n):
seen = []
while n > 0:
if n%10 in seen:
return False
seen.append(n%10)
n //= 10
return True
factors = [17,13,11,7,5,3,2]
possibles = {}
for k in factors:
n = 1
possible = []
while n*k < 1000:
if is_... |
#!/usr/bin/env python
import sys
from utils import seq_string
def build_factorials(n):
answer = [1]*n
for i in range(1,n):
for j in range(i,n):
answer[j] *= i
return answer
digit_factorials = build_factorials(10)
def digits(n):
return [int(c) for c in str(n)]
def factorial_che... |
#!/usr/bin/env python3
import sys
def prep(word):
word = word.strip()
if word[0] == '"':
word = word[1:-1]
return word
def read_words(infile,max_len=100):
answer = []
for line in infile:
answer += [prep(s) for s in line.split(',')]
answer = [w for w in answer i... |
#!/usr/bin/env python
def n3gon(n):
return n*(n + 1)//2
def n4gon(n):
return n*n
def n5gon(n):
return n*(3*n - 1)//2
def n6gon(n):
return n*(2*n - 1)
def n7gon(n):
return n*(5*n - 3)//2
def n8gon(n):
return n*(3*n - 2)
def gon_num(n,g):
if g == 3:
ret... |
def bubble_sort(elements: list) -> list:
for i in range(len(elements)):
for j in range(0, len(elements) - i - 1):
if elements[j] > elements[j + 1]:
elements[j], elements[j + 1] = elements[j + 1], elements[j]
return elements
def quick_sort(elements: list) -> list:
if len(... |
from dataclasses import dataclass
class Hero:
name: str
identity: str
company: str
height: float
weight: float
gender: str
eyes_color: str
hair_color: str
strength: int
intelligence: str
def __init__(self, name, identity, company, height, weight, gender, eyes_color, hair_c... |
"""
Flattens all nested lists (all levels), but does not extract members of other iterables.
For eficiensy in working with larger datasets, returns a generator object.
"""
def flatten_all(my_list):
for element in my_list:
if isinstance(element, list):
for nested_element in flatten_all(element):
yield nested_... |
#coding: utf-8
from dectofrac import *
print "CONVERSOR DECIMAL FRACIONÁRIO POSITIVO PARA BINÁRIO, OCTAL E HEXADECIMAL FRACIONÁRIO"
print "Para encerrar o programa, digite -1"
while True:
decimal = raw_input("Insira o número decimal a ser convertido, separado por vírgula: ")
if(decimal == "-1"):
break
print ... |
class Calculadora(object):
"""docstring for Calculadora"""
def __init__(self, nombre):
super(Calculadora, self).__init__()
self.nombre = nombre
def Suma(self,num1,num2):
return num1+num2
def Resta(self,num1,num2):
return num1-num2
def Multiplicacion(self,num1,num2):
return num1*num2
def Di... |
# -*- coding: utf-8 -*-
import copy
if __name__ == '__main__':
# single-dim array!!
print('shallow copy')
mylist = [3, 4, 5]
b = mylist
print(mylist, "\t**", b)
mylist[2] = -5
print (mylist, "\t**",b)
print('deep copy')
mylist = [3, 4, 5]
b = list(... |
"""
Отсортируйте по убыванию методом пузырька одномерный целочисленный массив, заданный случайными числами на
промежутке [-100; 100). Выведите на экран исходный и отсортированный массивы.
Примечания:
● алгоритм сортировки должен быть в виде функции, которая принимает на вход массив данных,
● постарайтесь сделать алг... |
"""
Написать программу сложения и умножения двух положительных целых шестнадцатеричных чисел.
При этом каждое число представляется как коллекция, элементы которой — цифры числа.
Например, пользователь ввёл A2 и C4F. Нужно сохранить их как [‘A’, ‘2’] и [‘C’, ‘4’, ‘F’]
соответственно. Сумма чисел из примера: [‘C’, ‘F’, ‘... |
"""
1.Написать программу, которая будет складывать, вычитать, умножать или делить два числа.
Числа и знак операции вводятся пользователем. После выполнения вычисления программа не
завершается, а запрашивает новые данные для вычислений. Завершение программы должно
выполняться при вводе символа '0' в качестве знака опера... |
""""
2.Посчитать четные и нечетные цифры введенного натурального числа. Например, если введено число 34560,
в нем 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5).
"""
answer = input('Введите набор чисел :')
a = 0
b = 0
for i in range(len(answer)):
if int(answer[i]) % 2 == 0:
a += 1
else:
b += 1... |
#!/usr/bin/env python
#Hello World Try It Out Exercise 7.1
#Ask the purchase price then display discount and final price.
price = float(raw_input("What is your purchase price: "))
if price <= 10:
print "Your discount will be 10%."
else:
print "Your discount will be 20%."
if price <= 10:
final = float( price ) * 0.... |
#!/usr/bin/env python
one = float(raw_input("\nPlease input a number with a decimal: "))
print "\nYour number as a float: ",one,"\n"
print "Your number an an integer: ",int(one),"\n"
|
#!/usr/bin/env python
#Hello World Try It Out Exercise 7.2
#Write a program to determine soccer team eligibility
print "We are going to determine your eligibility for Girls Club Soccer Team."
print "Are you a boy, girl, or other?"
sex = str(raw_input("Please use input m for boy and f for girl: "))
age = int(raw_input(... |
#!/usr/bin/env python
'''
lunar-eclipse-20180727.py
A simple python script to calculate the separation of
the Moon from the center of Earth's umbra. When the
separation is the lowest, then it is the peak of the eclipse.
This is for the lunar eclipse on July 27, 2018
'''
import ephem
from datetime import datetime, ti... |
import os
def main():
clear_screen()
welcome = "* Bem vindo, preguiçoso! *"
bot_top = "*"*len(welcome)
print("\n\t" + bot_top)
print("\t" + welcome)
print("\t" + bot_top + "\n\n")
print("Este programa é para quem tem preguiça de\n" +
"criar uma pasta dos exercícios do Dr. Fábi... |
import os
path = input("Enter path of File :")
file = [f for f in os.listdir(path) if f.endswith('.csv')]
for f in file:
print(f)
select = (int)(input("Enter number of file :"))
|
name = "Andy"
age = 20
print("Hi! My name is "+name+", and I am "+str(age)) |
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print(line)
def sing_song_backward(self):
# this doesn't copy, just points lyrics2 to the address of lyrics
# lyrics2 = self.lyrics... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.