text stringlengths 37 1.41M |
|---|
def w(func):
print('装饰的函数')
func(1,2)
return 1
@w
def inside(a,b):
print('被装饰的函数')
print(a,b)
return 2
inside
# s=inside
# print(s)
# def bracket(data):
# return data
#
#
# if __name__ == '__main__':
# # 不带括号调用的结果:<function bracket at 0x0000000004DD0B38>,a是整个函数体,是一个函数对象,不须等该函数执行完成
# ... |
# Code to Get Co-Ordinates
import math
import requests
import operator
def get_cords(my_lat,my_long,dist,angle):
"""The function get_cords() returns the user defined latitude and longitude coordinates in degrees"""
R = 3963.167 #Radius of the Earth in miles
brng = math.radians(angle) #B... |
# I am going to do some counting and math.
print "#1: What is 5 + 5?", 5 + 5
print "#2: What is 5 * 3?", 5 * 3
print "Is #1 greater than #2?", 5 + 5 > 5 * 3
print "Is #1 greater than equal #2?", 5 + 5 >= 5 * 3
print "Here is the second counting."
print "Do math:4 + 3 - 3 / 1 + 4 % 2 equals", 4 + 3 - 3 / 1 + 4 % 2 ... |
the_count = [1, 2, 3, 4, 5]
fruits = ['apple', 'orange', 'pears', 'appricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quaters']
# the first kind of for-loop goes through a list
for number in the_count:
print "This is count %d" % number
# same as above
for fruit in fruits:
print "A fruit of type: %s" % frui... |
#!/usr/bin/python
class Solution(object):
def hammingDistance(self,x,y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x^y).count('1')
if __name__ == '__main__':
x = int(input("input x :"))
y = int(input("input y :"))
print("Hamming Distance:",Solution().hammingDistance(x,y))
|
#!/usr/bin/python
class Solution(object):
def reverseWords(self,s):
'''
:type s : str
:rtype: str
'''
#return ' '.join(s.split()[::-1])[::-1]
return ' '.join(word[::-1] for word in s.split())
if __name__ == '__main__':
x = str(input("input a string:"))
print(Solution().reverseWords(x))
|
#!/usr/bin/python
class Solution(object):
def detectCapitalUse(self,word):
'''
:type word: str
:rtype: bool
'''
return word.isupper() or word.islower() or word.istitle()
if __name__ == '__main__':
x = str(input("input a string:"))
print("Capital detection:",Solution().detectCapitalUse(x))
|
# Name: Dusty Stepak
# Date: 04.12.2021
# Program: BruteForce.py
# Purpose: Create a brute force password cracking program in Python.
# This program asks the user to enter a password, and the
# program tries to crack it by checking all possible passwords
# with the characters a-zA-Z0-9. Se... |
#####################################
# Exercícios do site Codecombat.com #
# Autor: Rodrigo Vieira Peres #
# Data: 24/04/2016 #
# #
# Site: http://www.rodrigoperes.tk/ #
# #
# Arquivo: Lv7 - Loop Da Loop.py #
########... |
__author__ = 'madeira'
def average ( x, y, z):
if x > y:
if x > z:
if z > y:
return z
else:
return y
else:
return x
elif x > z:
return x
elif z > y:
return y
else:
return z
assert average (1,3,6)... |
"""
File: largest_digit.py
Name:
----------------------------------
This file recursively prints the biggest digit in
5 different integers, 12345, 281, 6, -111, -9453
If your implementation is correct, you should see
5, 8, 6, 1, 9 on Console.
"""
def main():
print(find_largest_digit(12345)) # 5
print(find_larg... |
# https://www.codewars.com/kata/51c8e37cee245da6b40000bd/python
def solution(string,markers):
lines = string.split('\n')
stripped_lines = []
for line in lines:
stripped_line = line
for marker in markers:
if marker in stripped_line:
stripped_line = stripped_line[0... |
def fibonacci(limit):
fib = [1,2]
limit_hit = False
while(not limit_hit):
next_fib = fib[len(fib)-1] + fib[len(fib)-2]
if next_fib < limit:
fib.append(next_fib)
else:
limit_hit = True
return fib
def main():
fibs = fibonacci(4000000)
print sum([x ... |
print(1 > 3)
print(2 < 4)
print(4 <= 5)
print(4 >= 5)
print(6 == 9)
print(6 != 9)
# 복합 관계식
a = 6
print(0 < a and a < 10)
print(0 < a < 10)
# 수치형 이외의 다른 타입의 객체 비교
print("abcd" > "abd")
print((1,2,4) < (1,3,1))
print([1,2,4] < [1,2,0])
# 동질성 비교 : ==, 동일성 비교 : is
print("동질성 비교")
a = 10
b = 20
c = a
print(a == b... |
from numpy import array
from numpy import mean
from numpy import cov
from numpy.linalg import eig
# define a small 5×3 matrix
matrix = array([[5, 6,3],
[8, 10,2],
[12, 18,4],
[8, 10,1],
[6, 12,5],])
print("original Matrix: ")
print(matrix)
... |
#!/usr/bin/env python3
# 12 - O python tem uma implementacão padrão de uma funcão sum para achar a soma dos elementos de uma lista, faca sua própria implementacão da funcão
#sum([1, 2, 3])
#6
index = int(input("Insira a quantidade de elementos: "))
def somaLista(index):
lista = []
for i in range(0, index):
... |
#!/usr/bin/env python3
#11 - Escreva uma funcão que imprima todos os números primos entre 0 e limit (um parâmetro).
limit = int(input("Insira o limite: "))
def prime(limit):
for i in range(2,limit+1):
multiplos = 0
for j in range(2,i):
if i % j ==0:
multiplos += 1
... |
import random
def selection_sort( arr):
for i in range(len(arr)):
midx = i
for j in range(i,len(arr)):
if arr[j] < arr[midx]:
midx = j
if midx != i:
arr[midx],arr[i] = arr[i],arr[midx]
return arr
def tester():
for _ in range(25):
... |
# Part one
with open("words.txt","r") as f:
words = set(word.rstrip() for word in f)
from itertools import permutations
def allwords(s, n=1):
perm = list()
while len(s) >= n:
p = permutations(s, n)
for i in p:
i = ''.join(i)
i = i.lower()
if i in words a... |
def extractfiles(zipf, regex):
import zipfile, os, re
zfile = zipfile.ZipFile(zipf, "r")
for f in zfile.namelist(): # Using the file list circumvents the underscore problem.
if re.match(regex, os.path.basename(f)):
zfile.extract(f, 'extractfilesresult') # Extracting to specia... |
# Problem link: https://www.codewars.com/kata/525c7c5ab6aecef16e0001a5/train/python
## Work in progress
wordMap = {
'one': 1,
'two': 2,
'three': 3,
'four': 4,
'five': 5,
'six': 6,
'seven': 7,
'eight': 8,
'nine': 9,
'ten': 10,
'eleven': 11,
'twelve': 12,
'thirteen': ... |
class EvenIterator:
def __init__(self, lst):
self.lst = lst
self.elem = 0
def __iter__(self):
return self
def __next__(self):
if self.elem < len(self.lst):
self.elem += 2
return self.lst[self.elem - 2]
else:
raise StopIteration
... |
# ex. 1
def sq(a, x):
res = []
count = 0
for i in range(0, x+1):
if i % 2 != 0:
res += [i**2]
count += 1
i += 1
print(*res, 'всего чисел -', count)
sq(0, 9)
# ex. 2
def div_by_c(a, b, c):
count = 0
for i in range(a+1, b):
if i % c == 0:
... |
import time
import sys
import random
number=random.randint(1,100)
def intro():
print("WELCOME TO GUESS THE NUMBER GAME\nHERE YOU NEED TO GUESS THE NUMBER")
time.sleep(1)
print("BETWEEN 1 TO 100\n5 CHANCES WILL BE GIVEN\nWITH SOME INTRESTING HINTS\n\n")
def lesser_or_greater(guess):
global num... |
# The game Fizz AND Buzz!
# multiple of 3 are POP
# multiple of 5 are TOC
# multiples of 3 and 5 are FizzBuzz
# as a user I should be ask for a number,
# so that I can play the game with my input
# As a player, I should see the game counting up to my number and
# substituting the multiples of 3 and 5 with the appropria... |
# Variables in Python
# A variable is a box. And we put stuff inside and give it a name
# Assign a variable
box_pillows = 'Pillows and stuff' # gave the box a name and put stuff inside
print(box_pillows) # Look inside a box
box_pillows = 'Books' # changing the stuff inside the box
print(box_pillows)
box_pillows... |
#Fruit Machine:
#Write a program to simulate a Fruit Machine that displays three symbols
#at random from Cherry, Bell, Lemon, Orange, Star, Skull.
#The player starts with £1 credit, with each go costing 20p.
#If the Fruit Machine “rolls” two of the same symbol, the user wins 50p.
#The player wins £1... |
arr = []
maxHourGlass = 0
row = 6
column = 6
for i in range(0, row):
temp_row = []
for j in range (0, column):
temp_row.append(int(input()))
#print(temp_row)
arr.append(temp_row)
#print(arr)
#print(arr)
for i in range(0, row - 2):
for j in range(0, column - 2):
sumHourGlass = arr[i][j] ... |
entryNo = int(input("How many records would you like to add?: "))
phoneNumber = dict()
def addNumber(Name, Number):
if Name in phoneNumber:
print("Error")
else:
phoneNumber[Name] = Number
for i in range (entryNo):
Name, Number = input("Enter the name and Number you want to add: ").split()
Name = Name.l... |
num=int(input("Enter a number"))
fact=1
for x in range (1,num+1):
fact =fact*x
print("Factorial of {} is {}".format(num,fact))
|
import numpy as np
from typing import Tuple, List
from numpy import sqrt
NN = np.nan
def in_range(data, minval=-np.inf, maxval=np.inf):
"""
Find values in range [minval, maxval).
Parameters
---------
data : np.ndarray
Data set of arbitrary dimension.
minval : int or float, optional
... |
inp = int(input('請輸入n,製造乘法表:'))
print("")
print("用if方式寫n*n乘法表")
for i in range(1,inp+1):
print("")
for j in range(1,inp+1):
print(f"{i}*{j}:{i*j}")
print("")
print("用while方式寫n*n乘法表")
print("")
a = 1
while 1 <= a <= inp:
b = 1
while 1 <= b <= inp:
print(f"{a}*{b}:{a*b}")
b += 1... |
n=int(input("enter a number"))
a=0
b=0
for i in range(2,n+1):
c=a+b
a=b
b=a
print(b, end=" ")
|
n=input("enter a number")
asc=n[0] <= n[1]
dsc=n[0] >= n[1]
i=1
while (i<(len(n)-1)):
if asc:
asc =n[i] <= n[i+1]
elif dsc:
dsc = n[i] >= n[i+1]
else:
break
i+-1
if asc:
print("ascending")
elif dsc:
print("decending")
else:
print("not found")
|
###################################
# INTERPOL, which stands for Integer Program Oriented Language, is a language specifically designed for IS 214 students.
# Compared to its IS 214 predecessors, INTERPOL is the simplest of them all.
# What makes it “integer oriented” is that the PL primarily deals with integers a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module Description:
This module is for converting dataset type.
"""
import numpy as np
import torch
import tensorflow as tf
from ai_dataset.types.keras import KerasData
from ai_dataset.types.torchvision import TorchData
def torch2keras():
pass
def keras2to... |
from fractions import Fraction
def solution(pegs):
dist = pegs[1]-pegs[0]
if len(pegs) == 2 and dist >= 3:
result=Fraction('2/3')*dist
return [result.numerator,result.denominator]
i=(3*dist)-1
while i >= 3 :
radius = i*Fraction('1/3')
candidate=assign(radiu... |
word=int('9'*309)
print('{} : {}'.format(len(word),word)) |
import itertools
def bananas(s) -> set:
res = set()
for comb in itertools.combinations(range(len(s)), len(s) - len('banana')):
sep = list(s)
for i in comb:
sep[i] = '-'
med_res = ''.join(sep)
if med_res.replace('-', '') == 'banana':
res.add(med_... |
# For directed graph nodes with edges with integer weights
class Node:
def __init__(self, id, name):
self.id = id
self.name = name
self.outgoingEdges = {}
return
def insertNeighbor(self, neighborNodeID, weight):
self.outgoingEdges[neighborNodeID] = weight
return
def getNeighborWeight(self, neighborNode... |
# 해당수가 소수인지 찾기
def find(n):
for i in range(2,n):
if(n%i==0):
return
print(n)
if __name__ == '__main__':
n = int(input())
for i in range(2,n+1):
find(i) |
from urllib import urlencode
import urllib2
import numpy
def get_historical_prices(symbol, start_date, end_date):
"""
Get historical prices for the given ticker symbol.
Symbol format is 'symbol'
Date format is 'YYYYMMDD'
By VC Analytics on 09/27/2014
"""
params = urlencode({
... |
def three_sum(nums):
"""Generate all tuples of three numbers in the input array which sum to 0.
The numbers must be at distinct indices in the array. Duplicate tuples are not allowed.
:param nums: an array of integers
:type nums: List[int]
:return: a list of tuples satisfying sum(t) == 0
:rtyp... |
# Задача №201. Числа Фибоначи
# https://informatics.mccme.ru/mod/statements/view.php?id=649#1
class FibonacciNumbers:
def __init__(self):
self.fibonacci_numbers = [None] * 45
def set_initial_states(self):
self.fibonacci_numbers[0] = self.fibonacci_numbers[1] = 1
def get_fibonacci_number(... |
def prime_definition(number):
answer = "prime"
for i in range(2, int(number ** 0.5) + 1):
if number % i == 0:
answer = "composite"
break
return answer
num = int(input())
result = prime_definition(num)
print(result)
|
from pprint import pprint
def create_list_members(count_members: int):
list_results_members = []
for i in range(count_members):
result_each_member = [int(i) for i in input().split()]
list_results_members.append(result_each_member)
return list_results_members
def bubble_sort(nums: list, ... |
# Задача №1170. Построение кучи просеиванием вниз
# https://informatics.mccme.ru/mod/statements/view3.php?id=1234&chapterid=1170#1
class BuildHeap:
def __init__(self, size_heap, list_elements):
self.heap_elements = list_elements
self.size_heap = size_heap
def presence_left_child(self, i):
... |
number_eng_words = int(input())
dict_latin_eng = dict()
for i in range(number_eng_words):
eng_word, all_translations_latin_words = input().split(' - ')
latin_translations = all_translations_latin_words.split(', ')
for latin_word in latin_translations:
if latin_word not in dict_latin_eng:
... |
number_countries = int(input())
dict_countries = dict()
for i in range(number_countries):
country_cities = input().split()
for city in country_cities[1:]:
dict_countries[city] = country_cities[0]
numb_find_cities = int(input())
for k in range(numb_find_cities):
find_city = input()
if find_ci... |
numbers_sentences = int(input())
set_words = set()
list_sentences = []
for i in range(numbers_sentences):
sentence = input().split()
list_sentences.append(sentence)
for sentence in list_sentences:
for word in sentence:
set_words.add(word)
print(len(set_words))
|
hours = int(input())
minutes = int(input())
seconds = int(input())
print(30 * hours + 0.5 * minutes + seconds / 120)
|
number = int(input())
digits_with_one_circle = "069"
digits_with_two_circles = "8"
count_circles = 0
try:
for symbol in str(number):
if symbol in digits_with_one_circle:
count_circles += 1
if symbol in digits_with_two_circles:
count_circles += 2
except str(number) == '':
... |
# Задача №764. Сбалансированность
# https://informatics.mccme.ru/mod/statements/view3.php?id=599&chapterid=764#1
class Node:
def __init__(self, value: int):
self.value: int = value
self.left: Node = None
self.right: Node = None
self.node_height = 0
self.is_balanced: bool = ... |
number_pairs_words = int(input())
dict_synonyms = dict()
for i in range(number_pairs_words):
pair_words_list = list(input().split())
dict_synonyms[pair_words_list[0]] = pair_words_list[1]
word_synonym_for_finding = input("Введите слово для нахождения:")
for key, value in dict_synonyms.items():
if key =... |
N = int(input())
sum_of_cubes = 0
for i in range(1, N + 1):
sum_of_cubes += (i ** 3)
print(sum_of_cubes)
|
def insertion_sort(list_nums: list, count_nums: int):
for i in range(1, count_nums):
x = list_nums[i]
index_prev_item_from_x = i - 1
while x < list_nums[index_prev_item_from_x] and index_prev_item_from_x >= 0:
list_nums[index_prev_item_from_x + 1] = list_nums[index_prev_item_fr... |
sentence = input()
while sentence.find(' ') != -1:
sentence = sentence.replace(' ', ' ')
print(sentence)
|
def leftside_binary_search(list_num: list, key: int) -> tuple:
"""Реализация левостороннего двоичного поиска"""
left_border = -1
right_border = len(list_num)
while right_border - left_border > 1:
mid = (left_border + right_border) // 2
if list_num[mid] < key:
left_border =... |
a = int(input())
b = int(input())
c = int(input())
minimal = a
if b < minimal:
minimal = b
if c < minimal:
minimal = c
print(minimal)
|
num_states = int(input())
dict_votes = dict()
for i in range(num_states):
name_president, num_votes_in_state = input().split()
if name_president not in dict_votes:
dict_votes[name_president] = int(num_votes_in_state)
else:
dict_votes[name_president] += int(num_votes_in_state)
for key, v... |
def bubble_sort(nums: list, count_nums: int):
swapped = True
num_exchanges = 0
while swapped:
swapped = False
for i in range(1, count_nums):
if nums[i - 1] > nums[i]:
nums[i - 1], nums[i] = nums[i], nums[i - 1]
num_exchanges += 1
sw... |
count_numbers = int(input())
list_numbers = [int(i) for i in input().split()]
inserted_number, index_inserted_number = map(int, input().split())
def insert_element(nums: list, ins_num: int, index_ins_num):
index_ins_num -= 1
nums = nums[:index_ins_num] + [ins_num] + nums[index_ins_num:]
return nums
for... |
x1 = int(input())
y1 = int(input())
x2 = int(input())
y2 = int(input())
if abs(x2 - x1) == 2 and abs(y2 - y1) == 1 or abs(x2 - x1) == 1 and (abs(y2 - y1) == 2):
print('YES')
else:
print('NO')
|
import csv
import sys
from livros import Livro
def main():
opcao = "0";
#Cria o menu e sai apenas quando selecionar a opção 6
while opcao != "6":
print()
opcao = input("""Selecione uma das opções abaixo:
1 - Cadastrar livro
2 - Listar todos os livros em o... |
def curdatfun():
from datetime import date
today = date.today()
print("Today's date:", str(today))
li=str(today).split('-')#1.0.1907.0
dyearcur=int(li[0][2:4])
dmonthcur=int(li[1])
return(dyearcur,3)
def mainfuncForNext():
n=input('enter:')
try:
li=n.split('.')
if len... |
x1=int(input("Введите число от 1 до 8"))
y1=int(input("Введите число от 1 до 8"))
x2=int(input("Введите число от 1 до 8"))
y2=int(input("Введите число от 1 до 8"))
if (x1+y1)%2==0 and (x2+y2)%2==0:
print("yes")
else:
print("NO")
|
import random
import os
class Food():
def __init__(self, meat=10, water=5, fish=8):
self.meat = meat
self.water = water
self.fish = fish
class Critter():
def __init__(self, name, hunger=100, boredom=100, sleep=100):
self.name = name
self.hunger = hunger
... |
from fractions import Fraction
#returns the expansion of the n'th iteration as a Fraction
def iterationApproximation(iteration):
numerator = 1
denominator = 2
for i in range(1,iteration):
numerator += (denominator*2)
#swapping the variables (division by a fraction)
tempNumerator = ... |
print("")
print("1.Listes")
print("1.1 Modifier une liste")
print("")
print("1.1.1 Supprimez les trois derniers éléments un par un, dans un premier temps")
print("")
annee = ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre',10,11,12]
x=0
while x <3:
annee.remove(len(annee))
x+=1
pr... |
def divisible_by(num, list_):
is_divisible = False
for n in list_:
if num % n == 0:
is_divisible = True
break
return is_divisible
divisibles = []
for number in range(1000):
if divisible_by(number, [3, 5]):
divisibles.append(number)
print sum(divisibles)
|
# coding=utf-8
# python3
def func():
print("Hello World")
class A:
name = "A"
def __init__(self):
self.id = 0
self.username = "beijing"
if __name__ == '__main__':
print(A.name)
print(A().username)
|
import re
import sys
class tracksInfo:
"""
Simply used to extracts the information of video which is generated by mkvmerge.exe
Constructor needs path to input txt file which contains information of the video.
"""
def __init__(self, infoFile=''):
try:
if infoFile == '':
raise Exception("- Err... |
#Converting miles into kilometers
miles = float(input("Enter miles:"))
kilometers = miles * 1.60934
print("Number of kilometers ={0:.3f}".format(kilometers))
|
# Longest Collatz sequense (14)
# 837799
def longest_Collatz_sequence(n):
longest_sequence = 0
for i in range(n+1, 2, -1):
sequence = 0
m = i
while m != 1:
if m % 2 == 0:
m = m / 2
sequence += 1
elif m % 2 == 1:
... |
# Prime permutations (49)
# 125925919521
import itertools
def sieve(limit):
numbers = list(range(2, limit+1))
primes = []
for i in numbers:
for m in numbers[numbers.index(i)+1:]:
if m % i == 0:
numbers.remove(m)
return numbers
prime_list = sie... |
# Even Fibonacci numbers (2)
# 4613732
def fib(n):
fib_list = []
a, b = 0, 1
while b < n:
a, b = b, a+b
if b % 2 == 0:
fib_list.append(b)
return(fib_list)
print(sum(fib(4*10**6)))
|
my_str = input('Enter several words: ')
line = my_str.split()
for n, word in enumerate(line, start=1):
print(n, word[:10])
|
# Task 1
def my_func(var_1, var_2):
try:
var_1, var_2 = float(var_1), float(var_2)
result = round((var_1 / var_2), 2)
except ValueError:
return 'You had to enter numbers'
except ZeroDivisionError:
return 'Деление на ноль невозможно'
return result
divided_var = my_func(... |
# # Task 1
a = 100
b = 200
print(a, b, sep=', ')
name = input('Введите ваше имя: ')
age = int(input('Введите ваш возраст: '))
print(name, age, sep=', ')
# # Task 2
time = int(input('Введите время в секундах: '))
hours = time // 3600
hours_left = time % 3600
minutes = hours_left // 60
minutes_left = hours_left % 60
s... |
my_list = list(input('Введите текст: '))
for i in range(1, len(my_list), 2):
my_list[i - 1], my_list[i] = my_list[i], my_list[i - 1]
print(my_list)
|
#date 2021.10.23
#author ltw
#dec 字典的遍历
myinfo={
'first name':'li',
'last name':'tianwang',
'age' :18,
'city':'beijing',
}
for key,values in myinfo.items(): #注意使用items转换为键值对列表
print(f'The people {key} is {values}')
print('\n')
revers={
'china':'changjiang',
'us':'mixixibi',
'aiji':'... |
''' -----------------------------------------------------------------
UNIVERSIDADE PAULISTA - ENG COMPUTAÇÃO - BACELAR
Nome: Mauricio Silva Amaral
RA : D92EJG-0
Turma : CP6P01
Data: 10/10/2021
Lista: 06 - 08
Enunciado: 08 – Escreva um programa que lê duas notas de vários
alunos e armazen... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""prefix expression
CHALLENGE DESCRIPTION:
You are given a prefix expression. Write a program which evaluates it.
INPUT SAMPLE:
Your program should accept a file as its first argument. The file contains one prefix expression per line.
For example:
* + 2 3 4
Your p... |
'''
Sequential Search
**Computational complexity**:
- best case = 1
- Worst Case = n
- Average Case = n/2
**Advantages**:
- Simple
- small data
**Disadvantages**:
- high computational complex
- big data is slow
- inefficient
'''
def busca_sequencial_for(lista, valor_procurado):
for i in range(len(lista... |
# A code snippet to demostrate the use of
# pandas python library
import pandas as pd
import math
import numpy as np
import matplotlib.pyplot as plt
# reading data from a file
data = pd.read_csv('data/food.csv')
print(data.head())
print('The size of the data set is' + str(data.shape))
print()
# Getting the names o... |
from Card import Card
import random
class Deck():
def __init__(self,symbols,cards_per_symbol):
self.cards = []
# TODO: nested list comprehension to make it faster
for name,symbol in symbols.items():
for card_number in range(1,cards_per_symbol+1):
... |
#!/usr/bin/python
from random import randint
def is_even(n): return n % 2 == 0
def square(n): return n**2
def expmod(base, exp, modu):
##your code
if (exp==0):
return 1
elif (is_even(exp)):
expm = expmod(base,exp/2, modu)
return (expm*expm)%modu
else:
return (base*expmo... |
STARTING_NUMBER_ERROR = "Please enter a 0 or 1!"
def fibonacci(starting_number, sequence_length=10):
if starting_number == 0:
a, b = 0, 1
elif starting_number == 1:
a, b = 1, 1
else:
print(STARTING_NUMBER_ERROR)
return
sequence = str(starting_number)
for i in range... |
from game.next_card import Dealer_card
class Dealer:
def __init__(self):
"""The class constructor.
Args:
self (Dealer): an instance of Dealer.
"""
# keep_playing is = to True, so that the game can start
self.keep_playing = True
# The user score
se... |
#
import numpy as np
total_tosses = 30
num_heads = 24
prob_head = 0.5
#0 is tail. 1 is heads. Generate one experiment
experiment = np.random.randint(0,2,total_tosses)
print ("Data of the Experiment:", experiment)
#Find the number of heads
print ("Heads in the Experiment:", experiment[experiment==1]) ... |
'''This file contains classes for modeling state parameters and modules.
The Estimator class represents a distribution over a scalar state variable
(e.g., the distance to the leader car, or the current agent's speed).
Estimators are grouped together in Modules, which use state variable estimates
of various world valu... |
#Exercise 19.1
'''from tkinter import messagebox
import tkinter as tk
class Window1:
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
self.button1 = tk.Button(self.frame, text = 'Press Me', width = 25, command = self.new_window)
self.butto... |
#Exercise 17.1
'''class Time(object):
def time_to_int(self):
minutes = time.hour * 60 + time.minute
seconds = minutes * 60 + time.second
return seconds
time = Time()
time.hour = 11
time.minute = 59
time.second = 30
print time.time_to_int()'''
#Exercise 17.2
'''class P... |
#Trevor Little- 3D Printed Statues
import sys, math, functools
statues= int(input())
numberOfPrinters= 1
numberOfStatuesPrinted= 0
days= 0
while numberOfStatuesPrinted < statues:
if (statues-numberOfStatuesPrinted) > numberOfPrinters:
days+=1
numberOfPrinters+= numberOfPrinters
... |
# 44.1 Namn och Ålder som string och int i en tuple.
'''
a = input("Namn: ")
b = int(input("Ålder:"))
t = (a, b)
print(type(a))
print(type(b))
print(t)
'''
# 44.2
'''
def switchT(t):
(a, b) = t
(a, b) = (b, a)
t = (a, b)
return t
t = (5, 6)
print(switchT(t))
'''
# 44.3
'''
def l_to_t(l):
return t... |
# 1 Bygg ett program som låter användaren mata in ett reg.nr och skriv ut de två grupperna
# var för sig; använd slicing-syntax för att dela upp inputsträngen. Klar!
def reg():
answer = input("Ange Regnummer: ")
bokstäver = answer[0:]
siffror = answer[3:]
print(f"Bokstävsgrupp: {bokstäver}\nSiffergru... |
# 40.1
def rev_text(text):
res = ''
for char in text:
res = char + res
return res
y = []
for i in text:
y.append(i)
# print(f"{y[4]}{y[3]}{y[2]}{y[1]}{y[0]}")
print("40.1")
print(rev_text("12345"))
print("\n")
# 40.2
def big_L(text):
upper = 0
for c in range(len(... |
from math import sqrt,cos,pi
import matplotlib.pyplot as plt
two_pi = 2*pi
takel_1 = []
takel_2 = []
takel_3 = []
takel_4 = []
takel_5 = []
takel_6 = []
phase = 0
length = 100
b=6
tilt=45
'''
square fucntion
for i in range(length):
output.append(sqrt((1+b**2)/((1+b**2)*(cos((two_pi*0)+phase)**2)))*cos((two_pi*0)+p... |
'''
Question:
Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5,
between 2000 and 3200 (both included).
The numbers obtained should be printed in a comma-separated sequence on a single line.
Hints:
Consider use range(#begin, #end) method
l=[]
for i in range(2000, 3... |
"""Object and functions for working with Loans for Game Simulations."""
from dataclasses import dataclass
import logging
log: logging.Logger = logging.getLogger(__name__)
@dataclass(kw_only=True)
class Loan:
"""Object to manage Loans in Game Simulations."""
name: str
balance: int
monthly_payment: ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.