text stringlengths 37 1.41M |
|---|
''' convert all keys below from camel case to snake case
read json and convert keys from camel to snake case.
testTest = test_test
'''
import json
def camel_to_snake(key1):
c = ''.join(['_' + c if c.isupper() else c for c in key1])
return c.lower()
def loop_dict(data, new_data):
for k,v in data.items():
... |
from tkinter import *
from PIL import Image, ImageDraw
import tensorflow as tf
import numpy as np
import os
# Determine model directory and path
cwd = os.getcwd()
model_dir = os.path.join(cwd, "model")
print("Model Directory: {}".format(model_dir))
model_path = os.path.join(model_dir, "modelMobilenet_3000samplesPerCla... |
# create a loop to put all the ascii characters in a list
def cipher (word, n):
list_of_word = list(word)
new_list_of_words = []
print ("original words: ", list_of_word)
for i in range (0, len(list_of_word)):
# uppercase
if (ord(list_of_word[i]) in range (65,91)):
new_pos = ord(list_of_word[i])+n
if new_... |
print("Caixa Registradora")
total = 0
produto = int(input("\nInforme o codigo do produto ou 0 para encerrar \nprodutos disponíveis 1 - 2 - 3 - 5 - 9: "))
if(produto != 0):
while produto != 0:
if(produto == 1):
total = total + 0.50
elif(produto == 2):
total = total +... |
# 1) Modifique o programa abaixo para exibir o que se pede:
# x=1
# while x<=3:
# print(x)
# x=x+1
# b) Exibir os números de 50 a 100.
x = 50
while x <= 100:
print(x)
x = x + 1
|
# design and devloped by webfun
# youtube channel --webfun
# email webbhalu@gmail.com
#for any kind of help please contact on 9096141591
from tkinter import *
import wikipedia
def get_me():
entry_value = entry.get()
answer_value = wikipedia.summary(entry_value)
answer.delete(1.0,END)
answer.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 3 12:06:30 2021
@author: orengoa0459
"""
# Description: This program is designed to help elementary school students(grades 2+), learn
# multiplication. The program consist of 3 difficulty levels (beginner,intermediate,expert)
# and 3 sub levels (le... |
#Import python support file
import random
import OrengoAnthony_game_functions as gameFunctions
# This program is a version of the "Rock", "Paper", "Scissors" game, using the python
#console. The user will have the option to play a 1, 2, or 3 round game. The winner will
#be display to the user upon completion of the ... |
from math import inf, sqrt
from tkinter import*
class Astar:
def __init__(self, heuristic_type, start, goal):
self.heuristic_type = heuristic_type
self.start = start
self.goal = goal
self.open_list = []
self.closed_list = []
self.solution = []
... |
class GetConfig():
"""This class reads the config.txt file and returns the latitude and longtitude"""
def __init__(self):
self.lines=self.loadConfigFile()
self.lat=self.findCoords(self.lines)[0]
self.long=self.findCoords(self.lines)[1]
def loadConfigFile(... |
"""
random随机数封装
"""
import random
import string
def random_str(n=20):
"""
随机生成一串密码
:param n: 密码的长度,默认为20
:return: 长度为n的随机字符串
"""
return ''.join(random.sample(string.ascii_letters + string.digits, n))
def random_small_number():
"""
随机生成一个小数
:return: 返回小数
"""
return random... |
import MapReduce
import sys
"""
Matrix Multiply Assignment in the Simple Python MapReduce Framework
"""
mr = MapReduce.MapReduce()
# =============================
# Do not modify above this line
def genkey(i, j):
return (i, j)
def mapper(record):
m = record[0]
i = record[1]
j = record[2]
v = re... |
# ********************************************* #
# Tiny Encryption Algorithm CBC Implementation #
# Ian Bolin & Trevor Loula #
# CS-3350 Foundations of Computer Security #
# ********************************************* #
import sys
import tea_algorithm
class TEA_CBC(tea_algorithm.TEA):
... |
'''
Pig Latin
'''
def pig_latin_word(word):
'''
Takes a word as a paramenter and translates it to pig latin.
'''
vowels = "aeiouAEIOU"
i = 0
const = []
for char in word:
if i == 0:
if word[0] in vowels:
return word+"way"
while word[0] not in vo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 23 10:01:26 2019
@author: hienh
"""
###############Task1############
#With a new line:
print ("What’s your age?")
Age = input()
#With a space:
Age = input("What’s your age? ")
#output data type is stringß
###############Task2############
print ("... |
def is_uppercase(inp):
checker = True
for i in inp:
if i == i.upper():
continue
elif i != i.upper():
checker = False
return checker |
#Task2
#Output question “What is your name?“, “How old are you?“, Where do you live?“.
# Read the answer of user and output next information: “Hello, (answer(name))“, “Your age is (answer(age))“, “You live in (answer(city))“
name = input("What is your name: ")
age = int(input("How old are you: "))
location =input("... |
sexo = str(input('Digite seu sexo?')).upper()
while sexo not in 'MmFf':
print('Digite um sexo valido')
sexo = str(input('Digite seu sexo?')).upper()
|
import math
n1 = int(input("ponto1 "))
n2 = int(input("ponto2 "))
n3 = int(input("ponto3 "))
n4 = int(input("ponto4 "))
distancia = math.sqrt(((n1-n2)**2)+((n3-n4)**2))
if distancia >= 10:
print("longe")
else:
print("perto") |
lista = []
while True:
continuar = input('Deseja adicionar um numero? [Sim ou Não] ').upper()
if continuar[:1] == 'N':
break
num = int(input('Digite um numero: '))
if num in lista:
print('Numero ja esta na lista')
else:
lista.append(num)
lista.sort()
print(lista) |
#Conjuntos
#listas são delimitadas por []
lista = [2, 4, 5, 3]
#lista.append(int(input("digite 1 numero: ")))
print(lista)
lista.sort()
print(lista)
#tuplas sao delimitadas por parenteses () elas sao imutaveis e uma alteracao ira gerar outra tupla
tupla = (10, 22, 44, 1)
print(type(tupla))
#mapas sao listas separa... |
N = "Samuel"
i = 25
print ("nome: {} idade: {}".format(N,i))
#indice: preencher / alinhar / largura / .precisão/
print ("nome {0:*^18.8} , idade {1}" .format(N,i))
#para strings
#indice : preencher/ alinhar/ largura/ .precisao
# <>^ 10 .2
#para Numeros
#indice : preencher/ alinhar/ sinal/ largura/ .precisao/... |
from random import randint
sorteio = []
i = 1
print('=' * 50)
print(' Mega Sena ')
print('=' * 50)
rodadas = int(input('Digite quantos jogos serão gerados: '))
while i <= rodadas:
for r in range(0, 6, 1):
sorteio.append(randint(1,60))
print(f'A Rodada {i} resultou em: {sorteio}... |
from typing import List # not needed when we upgrade to 3.9
def print_names_to_columns(names: List[str], cols: int = 2) -> None:
for i, name in enumerate(names, start=1):
print(f'| {name}\t'.expandtabs(12), end='\n' if not i % cols else '')
|
from typing import List, Union
def join_lists(lst_of_lst: List[List[str]], sep: str) -> Union[List[str], None]:
if not lst_of_lst:
return None
new_list = lst_of_lst[0]
for i in lst_of_lst[1:]:
new_list.append(sep)
new_list.extend(i)
return new_list
|
#Calculate and print the sum of the elements in an array, keeping in mind that some
#of those integers may be quite large.
#Input Format
#The first line of the input consists of an integer .
#The next line contains space-separated integers contained in the array.
#Output Format
#Print the integer sum of the elem... |
#Alice and Bob each created one problem for HackerRank. A reviewer rates the two challenges,
#awarding points on a scale from 1 to 100 for three categories: problem clarity, originality,
#and difficulty.
#We define the rating for Alice's challenge to be the triplet A=(a[0], a[1], a[2]), and the
#rating for Bob's ch... |
Task
Read an integer . For all non-negative integers , print . See the sample for details.
Input Format
The first and only line contains the integer, .
Constraints
Output Format
Print lines, one corresponding to each .
Sample Input 0
5
Sample Output 0
0
1
4
9
16
Current Buffer (saved locally, editable)
... |
import pandas
def load_all_df():
return pandas.read_csv('./raw_data/all_yob.csv')
def df_iterator():
for year in range(1880, 2014):
file_name = 'raw_data/yob' + str(year) + '.csv'
df = pandas.read_csv(file_name)
df['year'] = year
yield df
return
|
#import files
import os
import csv
# Path to collect data from the Resources folder
poll_analysis = os.path.join('..','resources','election_data.csv')
# Create empty lists to iterate through specific rows for the following variables
votes=0
khan_votes=0
correy_votes=0
li_votes=0
otooley_votes=0
# Open and read csv
w... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the timeInWords function below.
def timeInWords(h, m):
d = {0:"zero",
1: "one",
2:"two",
3:"three",
4:"four",
5:"five",
6:"six",
7:"seven",
8:"eight",
9:"nine"... |
def capturar():
b = True
while b:
q = int(input("QUIZ: "))
if (q < 0) or (q > 100):
print("Intente nuevamente.")
else:
b = False
while b == False:
p = int(input("PARCIAL: "))
if (p < 0) or (p > 100):
print("Intente nuevamente.")
... |
from time import *
import sys
class ONPyTimer(object):
'''
ONPyTimer allows to monitor time difference between the lines of a
Python script in a stopwatch-like manner.
=== Usage: =====================
from ONPyTimer import *
ONPyTimer.check(flag='A') # will show current time and flag name
...
ONP... |
#2017-1-7 16:48:5033
#字符串的替代;
str1 = "Hello, i am the Hello kitty!"
#替换第一个;
str2 = str1.replace("He","he",1)
print(str2)
#替换全部;
str3 = str1.replace("He","he")
print(str3)
#替换第二个
str4 = str1.replace("He","he",2)
print(str4)
|
#2017-1-8 15:42:04
#list tuple dic 列表,元组,字典;
nameList1 = ["mark", "lily", "lucy"]
nameTuple = ("mark", "lily", "lucy")
nameDic = {"name1":"mark", "name2":"lily", "name3":"lucy"}
#输出
print(nameList1)
print(nameTuple)
print(nameDic)
#修改nameTuple的值
'''
当尝试修改元组的内容时候会error;
'''
#nameTuple[0] = "park"
... |
from tkinter import *
from itertools import combinations
def generate_the_numbers():
'''
The main function that generates the numbers.
'''
quantity_ = entry_quantity.get()
sum_n = entry_sum.get()
quantity = int(quantity_)
sum_ = int(sum_n)
numbers = range(1, 10)
res_num = [z for z ... |
#!/usr/bin/env python3
#Chaz Davis
#CIT 144 Spring 2015
#Program I: Temperature Conversion 2/6/2015
#defining variables
temperature1 = 0.0
temperature2 = 0.0
conversion = ""
#retrieving data from user
temperature1 = int(float(input("What temperature would you like to convert")))
conversion = input("Please enter a C... |
numero = float(input('Digite um numero qualquer: '))
print(numero / 5) |
"""Generate Markov text from text files."""
from random import choice
from sys import argv
def open_and_read_file(file_path):
"""Take file path as string; return text as string.
Takes a string that is a file path, opens the file, and turns
the file's contents as one string of text.
"""
# your ... |
#! /usr/bin/env python3
import math
#print entire table
def print_table(table, l, e = "\t", line = "_______"):
for i1 in range(l):
if i1 > 0:
for i2 in range((l + 1) * l - 1):
print(line, end = e)
print("")
for i2 in range(l):
for j in range(l):
if j > 0:
print("|", end = e)
for k in r... |
from hash_tables import dict_wrapper, hash_table, set_wrapper
def two_sum(ints, t, populated_hash_table):
"""2-sum algorithm.
Given a set of integers ints and an integer t, return True if
there exist distinct elements x and y in ints such that x + y == t
"""
for x in ints:
y = t - x
... |
"""Given a stream of 10,000 numbers, compute the median
among the numbers seen so far
"""
from heaps import Heap as MinHeap, MaxHeap
def main():
with open("Median.txt", "r") as f:
numbers = f.readlines()
numbers = [int(line.strip()) for line in numbers]
print(calculate_medians(numbers))
def c... |
import itertools as it
from union_find import Node, union, find
def main():
K = 4 # Desired number of clusters
with open('clustering1.txt', 'rt') as file:
cluster_cnt = int(file.readline()) # First line is count of nodes
edges = file.readlines()
edges = [
tuple([int(x) for x i... |
from collections import namedtuple
from heap import Heap
Job = namedtuple('Job', ['weight', 'length', 'score'])
def main():
with open('jobs.txt', 'r') as file:
file.readline() # Ignore top (header) line of file
lines = file.readlines()
lines = [tuple(line.split()) for line in lines]
lin... |
def lucky_number(name):
number = len(name) * 9
check = "Hello " + str(name) + ". Your lucky number is " + str(number)
return check
print(lucky_number("Kay"))
print(lucky_number("Cameron"))
|
def leap_year(year):
if year % 400 is 0 or year % 4 is 0:
print("%d is a leap year" % year)
return True
else:
print("%d is not a leap year" % year)
return False
# tests
leap_year(2000) # yes
leap_year(2001) # no
|
# arr=[1,2,3,'a','ehllo',1+2j]
# print(arr)
# tup=(1,2,3,'1',2+3j)
# print(tup)
# dictionary={'one':1,'two':2,3+3j:3}
# print(dictionary)
# a=10
# b=2
# add=a+b
# sub=a-b
# mul=a*b
# div=a/b
# rem=a%b
# exp=a**b
# flrdiv=a//b
# print(add)
# print(sub)
# print(mul)
# print(div)
# print(rem)
# print(exp)
# print(flrdiv)
... |
class stack():
def __init__(self):
self.item = []
def push(self, data):
return self.item.append(data)
def pop(self):
return self.item.pop()
def get_stack(self):
return self.item
def is_empty(self):
return self.item == []
def peak(self)... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def constructMaximumBinaryTree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
Node = TreeNode(max(nums))
if nums[0]==max(nums):
... |
import pandas as pd
class DataframeMonthwiseSplitter:
def __init__(self, file_name):
self.file_name = file_name
self.data_frame = pd.read_csv(self.file_name, low_memory=False)
print("The file name is: {}".format(self.file_name))
print('DataFrame Dimensions:', self.data_frame.shape)... |
#!/usr/bin/env python3
"""problem2.py: solution to Project Euler Problem 2. 'projecteuler.net/problem=2'"""
___author___="Jeremy Minton"
___status___="Passed"
upperLimit = 4e6;
sum = 0;
first = 1;
second = 1;
while first<upperLimit or second<upperLimit:
first += second;
second = first-second;
if first%2=... |
mail = input("Enter your mail id: ")
username = mail[: mail.index('@')]
domain = mail[mail.index('@')+1:]
print(f"Your username is '{username.upper()}' and your domain is '{domain.upper()}' " ) |
from random import randint
class RandomPlayer():
"""Player that chooses a move randomly."""
def move(self, game, legal_moves, time_left):
if not legal_moves: return (-1,-1)
return legal_moves[randint(0,len(legal_moves)-1)]
class HumanPlayer():
"""Player that chooses a move according to
... |
'''
Your function should take in a single parameter (a string `word`)
Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''
def count_th(word):
# if the length of the word is less than or eq... |
#문제 이해를 못하겟다... 교차하는 연결리스트라는게 무슨 말이지?? -> 일단 풀긴 했음
from Chap2.LinkedList import LinkedList
def solution(ll_a, ll_b):
longll,shortll = ll_a if len(ll_a)>=len(ll_b) else ll_b,ll_a if len(ll_a)<len(ll_b) else ll_b
flag = True
nowShort = shortll.head
nowLong = longll.head
for i in range(len(longll)-... |
#먼저 온 애가 먼저 나가야 하니까 FIFO QUEUE
class Queue():
order = 0
dogqueue = []
catqueue = []
def dequeueAny(self):
if (len(self.dogqueue) > 0) or (len(self.catqueue)>0):
firstAnimal = self.dogqueue if self.dogPeek()[0] < self.catPeek()[0] else self.catqueue
else:
return F... |
class Stack():
stack = []
def pop(self):
if len(self.stack) > 0 :
result = self.stack.pop()
else:
result = None
print("Out of range")
return result
def push(self,item):
self.stack.append(item)
def peek(self):
return self.stac... |
from board import board
import time
class game:
def __init__(self,length,initial_board,game):
self.length=length
self.initial_board=initial_board
self.game=[self.initial_board if i==0 else None for i in range(0,self.length)]
def construct_game(self):
for i in range(0,self.leng... |
"""SecTalks CTF101 - 02 - Cryptoanalysis
Brute-force Caesar cipher
"""
cipher = 'FVBJHUIYLHRJVKLHUKFVBHYLWYVBKVMPA'
#cipher = 'FRPGNYXFZRRGHCFNERNOBHGCNEGVPVCNGVATVAVGFRPHEVGLQVFPHFFVBAFYRNEAVATSEBZBGUREFNAQVZCEBIVATCEBOYRZFBYIVATFXVYYF'
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for key in range(len(LETTERS)):
plain... |
#Clase de programacion
#Proyecyo: Tiempo de Vida
#Autor: Carredano Ochoa Elisa
#Carnet: 16285-20
#Este programa encontrara el tiempo de vida de una persona en base a su fecha de nacimiento
from datetime import date
#Fecha de hoy
hoy = date.today()
#obtener el dia de hoy
dia = hoy.day
#mes obtener el m... |
# Program to sort names in phones.txt
phones = {}
with open("phones.txt", "rt") as r:
for line in r:
parts = line.split(",")
print(parts)
if len(parts) != 2:
continue
if parts[1].strip("\n").isdigit():
phones[parts[0]] = parts[1].strip("\n")
... |
# # A la antigua
a = [1, 10, 5, 3, 8]
b = [8, 80, 100, 3, 10]
c = list()
notrepeted = 0
for item1 in a:
for item2 in b:
if item1 != item2:
notrepeted = 1
else:
notrepeted = 0
break
if notrepeted:
c.append(item1)
for item1 in b:
for item2 in a:
... |
def primes(n):
""" Returns a list of primes < n """
sieve = [True] * n
for i in xrange(3,int(n**0.5)+1,2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1)
return [2] + [i for i in xrange(3,n,2) if sieve[i]]
primesList = primes(987654322)
pandigitalSet = set()
a... |
prime = 0
num = 2000000
primes = []
total = 0
for i in range(2,num):
test = True
for m in range(2, int(i**0.5)+1):
if (i % m == 0):
test = False
break
if test == True:
primes.append(i)
total+=i
|
def primes(n):
""" Returns a list of primes < n """
sieve = [True] * n
for i in xrange(3,int(n**0.5)+1,2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1)
return [2] + [i for i in xrange(3,n,2) if sieve[i]]
primeList = primes(100000)
tableSize = max(primeList)+1... |
import numpy as np
class DataGenerator:
"""A gaussian mixture random data generator"""
def __init__(self, num_components, component_means, component_standard_deviations):
"""
Make a data generator with some number of specified gaussian components
:param num_components: an int
:p... |
import pandas as pd
import os, nltk, re, time
from nltk.util import ngrams
from nltk.corpus import stopwords
from collections import Counter
# global variable for the stop word list, with language definition
STOP_WORDS = set(stopwords.words('english'))
# time stamp format
timestr = time.strftime("%Y-%m-%d_%H-%M... |
import random
import time
today = [0,0] #玩家出生位置
to = [5,5] #追逐目标位置
crazy = [random.randint(0,4),random.randint(0,4)] #怪物出生位置
end3 = []
end1 = [] #读取存档用数据·
end2 = []
game = 0
class move():
def left(*args):
if today[0] < 1:
print(f'您已经到达最左侧,当前位置为({today[0]},{today[1]})')
else:
... |
# print("hello world!") #字符串
# print(True) #布尔值
# print(2333) #整数
# print(2.22) #小数
# print(()) #元祖
# print([]) # 数组
# print({}) #字典
# print("hello world!",2333)
# print("哈哈"+"嘻嘻") #字符串带拼接,只能相同的数据类型
# print("哈哈"*10)
# print(1+2)
# print(2>3)
# print(2<3)
# a="张三" #把张... |
# Define Level in list of objects
level = []
rooms_by_level = []
# Initialize Rooms and Level
def initialize_level(levelnew,room):
if levelnew and room:
for i in range(5):
level_and_room = {"level":i, "room":room, "available_room":room,"alloted_room":0}
level.append(level_and_room)
... |
from math import sqrt
x = int(input())
cnt = 0
for i in range(1, sqrt(x).__int__()+1):
if x % i == 0:
cnt += 1
if i != x/i:
cnt += 1
print(cnt)
|
a = 0.1
b = 1 / 10
if a <= b:
print('same')
else:
print('different'
a = 1
b = 3
if (a == 1) or (b == 3):
print('oui')
else:
print('non')
if (a == 1) and (b == 3):
print('oui')
else:
print('non')
print('1+1-1')
a = input()
b = float(a)
c = str(b)
print(type(b))
if (b != 1):
print('fau... |
def insertionSortRecursive(arr,n):
if n>1:
insertionSortRecursive(arr,n-1)
x = arr[n]
i = n-1
while (i>0 and arr[i]>x):
arr[i+1] = arr[i]
i = i-1
arr[i+1]=x
arr = [1,5,3,4,8,6,3,4,5]
n = len(arr)
insertionSortRecursive(arr, n)
print("Sorted array is:")
for i in range... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author : pingcuo
# Blog :
# Date : 2019-08-21
# Name : time_clac
# Software : vscode
# Note :
# 导入模块
import math
from .my_math_model import my_round
# 60进制转10进制
def to_dec(num) :
minute = math.floor(num)
second = (num - minut... |
"""
Basic example on how to grant an achievement.
"""
import os
import sys
import time
if sys.version_info >= (3, 8):
os.add_dll_directory(os.getcwd()) # Required since Python 3.8
from steamworks import STEAMWORKS # Import main STEAMWORKS class
"""
In this example, we'll set up a basic achievement. We'll assume ... |
# This function calculates how much $ you'll have in X years, if you invest weekly.
# How much are you investing per week?
weekly_in = 100
# How many years do you plan on investing for?
num_years = 10
# Compound Annual Growth Rate (ROI %)
cagr = 15
def investing(weekly_in, num_years, cagr):
cagr = (100+cagr)/100
... |
import re
"""
This file is the implementation of the re module that allows us to
split, parse strings
"""
def parseargs(string):
result = string.split()
return result
def parse_spaces(string):
"""
This function parses the input string splitting spaces between the
different commands.
@param s... |
"""
Using the Python language, have the function VowelSquare(strArr) take the strArr parameter being passed which will be a
2D matrix of some arbitrary size filled with letters from the alphabet, and determine if a 2x2 square composed entirely
of vowels exists in the matrix.
If a 2x2 square of vowels is found your prog... |
"""
Using the Python language, have the function LongestWord(sen) take the sen
parameter being passed and return the largest word in the string.
If there are two or more words that are the same length, return the first word
from the string with that length. Ignore punctuation and assume sen will not be empty.
"""
def... |
import sqlite3 as lite
import os
# Method to interact with our databse of cars
def createNewCarInDB(manu, model, year):
databaseName = "carObjects.sqlite"
carDBExists = not os.path.exists(databaseName)
tableName = "listOfCars"
connection = lite.connect(databaseName)
cursor = connection.curso... |
# Represents a Huffman tree for use in encoding/decoding strings.
# A sample usage is as follows:
#
# h = HuffmanTree([('A', 2), ('B', 7), ('C', 1)])
# assert(h.encode('ABC') == '01100')
# assert(h.decode(h.encode('ABC')) == 'ABC')
class HuffmanTree:
# Helper object for building the Huffman tree.
# You may modify ... |
# coding : utf-8
'''生成器求斐波那契数列'''
def fib_genarator(n):
n1, n2, count = 1, 1, 2
yield n1
while count <= n:
tmp = n2
n2 = n1 + tmp
n1 = tmp
yield n1
count += 1
counts = int(input("请输入需要的数列的项的个数: "))
res = fib_genarator(counts)
print(list(res))
|
nome = input ('Qual é o seu nome ? ')
idade = input ('Qual é o seu nome ? ')
peso = input ('Qual é o seu nome ? ')
print(nome,idade,peso)
|
class NegBalance(Exception):
pass
class AddNeg(Exception):
pass
class MinBal(Exception):
pass
class BankAccount:
def __init__(self,amt=0):
self.num=amt
def deposit(self,amt=0):
try:
if amt<0:
raise(AddNeg)
else:
pass
except AddNeg:
print("Can't deposit negetive... |
def generate_n_chars(n, c):
s=""
s=s+(n*c)
return s
print(generate_n_chars(5,"x")) |
class City:
def __init__(self,name="default",places=[]):
self.name=name
self.places=places
def addplace(self,place):
self.places.append(place)
def remplace(self,place):
self.places.remove(place)
def printplace(self):
for p in self.places:
print(p)
while(1):
i=int(input("1.Enter C... |
import bisect
import collections
import math
__all__ = ['Histogram']
class Bin:
"""A Bin is an element of a Histogram."""
__slots__ = ['left', 'right', 'count']
def __init__(self, left, right=None, count=1):
self.left = left
self.right = left if right is None else right
self.co... |
#!/usr/bin/env python3
from Crypto.Util.number import *
from flag import flag
nbit = 64
while True:
p, q = getPrime(nbit), getPrime(nbit)
P = int(str(p) + str(q))
Q = int(str(q) + str(p))
PP = int(str(P) + str(Q))
QQ = int(str(Q) + str(P))
if isPrime(PP) and isPrime(QQ):
break
n = PP * QQ
m = bytes_to_long(f... |
from random import randrange
from math import ceil
class Graph(object):
'''
Simple Graph representation
'''
def __init__(self, n, undirected = True):
'''
The constructor - creates graph with given n vertices.
n - number of vertices
undirected - True if graph should be ... |
import random
to_do = [
'Why don\'t you eat some fucking',
'How about some fucking',
'Eat a pile of fucking',
'Will you please fucking eat',
'Eat some GOD damn fucking',
'Cook up some fucking',
'You will not make some fucking',
'Try some fucking',
'The New England ... |
def max_num(num1, num2, num3):
if num1 > num2 and num1 > num3:
return num1
elif num2 > num1 and num2 > num3:
return num2
elif num3 > num1 and num3 > num2:
return num3
else:
return "It's a tie!"
print(max_num(int(input('Enter number 1: ')), int(inp... |
def username_generator(first_name, last_name):
username = first_name[:3] + last_name[:4]
return username
def password_generator(user_name):
password = ""
for i in range(0, len(user_name)):
password += user_name[i-1]
return password
|
import os
import math
import json
import random
import numpy as np
import networkx as nx
from abc import ABC, abstractmethod
from copy import deepcopy
from typing import List
class State(ABC) :
"""
This abstract class represents a discrete state in a reiforcement learning problem.
The abstract methods sho... |
# author: Yannik Stumpp
# date: 21.03.2020
from tile import Tile
class Board:
#================================================================================
# short: this function is the init function
#--------------------------------------------------------------------------------
# long:
# t... |
def detect_triangle(a, b, c):
#if (type(a) != float and type(a) != int) or (type(b) != float and type(b) != int) or (type(c) != float and type(c) != int):
#return 'khong dung kieu'
if (a > 2**32 - 1) or (b > 2**32 - 1) or (c > 2**32 - 1) or (type(a) not in [int, long, float]) or (type(b) not in [int, l... |
from get_longest_all_palindromes import get_longest_all_palindromes
from get_longest_prime_digits import get_longest_prime_digits
from get_longest_digit_count_desc import get_longest_digit_count_desc
def list_input() -> [int]:
"""
Functia care permite introducerea numerelor.
:return: Numerele introduse su... |
n=int(input())
f=1
if n<2:
print(f)
else:
for i in range(1,n+1):
f*=i
print(f)
|
#!/bin/env python
"""
get_http_codes.py
Purpose: reads https access log, and prints occurences of codes
Usage:
-f|--file file name
Examples:
python get_http_codes.py -f access.log
Author: Dovi Klausner
Date: 04/2021
"""
import argparse
from apachelogs import LogParser
import json
def parse_parameters... |
import sys
import os
import string
import random
def continuar_jogando():
print("\n[ 0 ] - Sair\n[ 1 ] - Jogar")
escolha = int(input("\nResposta: "))
if escolha == 0:
exit()
elif escolha != 1:
os.system('cls' if os.name == 'nt' else 'clear')
input("Entrada inválida. Tente novam... |
class Account:
def __init__(self, name: str, number: str, balance: float) -> None:
self.__name = name
self.__number = number
self.__balance = balance
def deposit(self, amount: float):
if amount <= 0:
print('存款金額不得為負')
else:
self.__balance += amoun... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.