text
stringlengths
37
1.41M
''' If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. ''' from functools import reduce result = reduce(lambda t, i: (t + i) if i % 3 is 0 or i % 5 is 0 else t, range(1000), 0) print(...
class Node(object): def __init__(self, elem): self.elem = elem self.next = None class SingleLink(object): def __init__(self, node=None): self.__node = node def is_empty(self): return self.__node == None def length(self): cur = self.__node cout = 0 ...
import sys x = str(sys.stdin.readline()).replace('\n', '').split(' ') #print x def rpn(input): for i in xrange(len(x)): if x[i] is "false": x[i] = "False" elif x[i] is "true": x[i] = "True" operators = ["+", "*", "==", "and", "or"] boolops = ["and", "or"] stac...
import sys r = str(sys.stdin.readline()) def reversal(word): if len(word) == 1: return word else: return reversal(word[1:]) + word[0:1] ans = reversal(r) print ans
""" Solving 8puzzle with astar algorithm Input files are plain text, written as 3 lines: the start state. They must include the numbers 0-8, where 0 represents the empty space, and 1-8 the 8 tiles of the puzzle. Here is an example of a properly formated state: 1 2 0 3 4 5 6 7 8 """ import sys import math import heapq ...
def machine(): keys = 'abcdefghijklmnopqrstuvwxyz !' value = keys[-1]+keys[0:-1] # this line is up to designer i can change it yhe way i want encry = dict(zip(keys,value)) decry = dict(zip(value,keys)) msg=input("enter the message ") mode=input("enter E for encryption and enter D for decry...
from typing import List class Solution: def containsDuplicate(self, nums: List[int]) -> bool: # return self.__bruteForce(nums) # return self.__sorting(nums) return self.__hashset(nums) # time complexity: O(n**2), space complexity: O(1) def __bruteForce(self, nums: List[int]) -> boo...
from collections import defaultdict class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: # return self.__brute_force(ransomNote, magazine) return self.__hash_map(ransomNote, magazine) # n is the size of ransomNote, m is the size of magazine # time complexity: O(n...
""" 1.Роздрукувати всі парні числа менші 100""" #while start = 0 finish = 100 i = 0 while start < finish: print(start) start+=2 #for for j in range(2,100,2): print (j) """ 2.Роздрукувати всі непарні числа менші 100""" # odd number for j in range(1,100,2): print (j) # odd number continue for val in rang...
import this zen_of_python='''Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beat...
#!/usr/bin/env python #-*- coding:utf-8 -*- # ################# 练习:计算圆的周长 ################# from math import pi class Circle: def __init__(self,radius): self.radius = radius @property def area(self): area = pi * (self.radius ** 2) return area @property def perimeter(self...
# edad = int(input("Escribe tu edad: ")) # if edad >= 18: #los dos puntos indican que es una condicional # #pass #es una instruccion vacia, sirve para saltar una linea y luego completarla # print("Eres mayor de edad") # else: # print("Eres menor de edad") numero = int(input("Escribe un numero: ")) if numer...
""" ID: isaiahl1 LANG: PYTHON2 TASK: combo """ TASK = 'combo' def readints(fin): return tuple(int(x) for x in fin.readline().split()) def readint(fin): return int(fin.readline()) def main(fin, fout): N = readint(fin) sol1 = readints(fin) sol2 = readints(fin) print 'sol', sol1, sol2 count = 0 for a in xrange(...
#sets examples import sys #A set is like a dictionary with its values thrown away, leaving only the keys #key must by unique #Sets are to prove existence and nothing else #Create a set you can use the set() function #Or enclose one or more comma-separated values in curly brackets empty_set = set() e...
numberone = int(input ("Enter a number ")) numbertwo = int(input ("Enter a second number ")) print (numberone + numbertwo)
class Laser: def does(self): return 'disintegrate' class Claw: def does(self): return 'crush' class SmartPhone: def does(self): return 'ring' class Robot: def __init__(self): self.laser = Laser() self.claw = Claw() self.smartphone = SmartPhone() def does(self): return """I have many attachments: M...
start1 = ["fee", "fie", "foe"] rhymes = [ ("flop", "get a mop"), ("fope", "turn the rope"), ("fa", "get your ma"), ("fudge", "call the judge"), ("fat", "pet the dog"), ("fun", "say we're done"), ] start2 = "Someone better" start1_caps = " ".join([word.capitalize()...
a=[1,2,3,4,5,6,7,8,9] b=[] if not a: print("A is Empty List") else: print("List A is: "+str(a)) print("\n") if not b: print("B is Empty List") else: print("List B is: "+str(b))
d = {} print(d) d['a'] = 100 d['c'] = 3 d['d'] = 4 d['b'] ="hi" d['f'] ="hello" print(d)
list = [] n = int(input("Enter number of elements : ")) for i in range(0, n): element = int(input()) list.append(element) print(list,"\n") print("Even Elements in the list are:") for n in list: if n % 2 == 0: print(n, end = " ")
try: fn = input('Enter filename: ') with open(fn,'r') as fi: for line in fi: words = line.split() for word in words: print(word) except: print('BADNESS!!!')
# Abstraction!!!! # Functions : encapsulations of logic prod = 1 for x in range(1, 5): # 1..4 print(str(x) + ' * ' + str(prod)) prod = prod * x print(' = ' + str(prod)) print('4! = ' + str(prod)) prod = 1 fact = 5 for x in range(1, fact + 1): # 1..4 print(str(x) + ' * ' + str(prod)) prod =...
total = 0 while True: inp = input('Enter a number (press Enter to stop): ').strip() if inp == '': # len(inp) == 0 // not inp break elif not inp.isnumeric(): print('Enter a number, moron') else: num = int(inp) total += num print(f"You're subtotal so far is {total...
# boolean expression # EVALUATES to True or False # res = True # THESE TWO ARE EQUIVALENT # if res == True: # if res: # Comparisons: <, >, <=, >=, ==, !=, in, not in, is, is not "a" != "A" ord('a') # 97 ord('A') # 65 'a' > 'A' # True l = ['abc', 'abd', 'abZ', 'ZZZ'] l.sort() print(l) (1,2,3) < (1,3,2) (1,2,10...
# TYPES OF STREAMS # File Stream # seekable # readable # writable # stdout (OUTPUT STREAM) # stdin (INPUT STREAM) # stderr (ERROR OUTPUT STREAM) f = open('simpletable.html') if f.readable(): contents = f.read(10) print(contents) contents = f.read(10) print(contents) if f.seekable(): ...
# 将一条消息存储到变量中,将其打印出来;再将变量的值修改为一条新消息,并将其打印出来 message = "Hello world!" print(message) message = "Hello python!" print(message)
# 创建一个待验证用户列表和一个存储已验证用户列表 unconfirmed_users = ['alice', 'brian', 'candace'] confirmed_users = [] # 验证每个用户,知道没有未验证用户为止 while unconfirmed_users: current_user = unconfirmed_users.pop() print("Verifying user: " + current_user.title()) confirmed_users.append(current_user) # 显示所有已验证用户 print("\nThe following use...
""" First class example """ class Dog: """Define a dog""" species = 'mammal' def __init__(self, name, age): self.name = name self.age = age def get_age(self): """Return the dog's age""" return self.age def get_name(self): """Return the dog's name""" ...
""" Inheritance example """ class Person: """Define a person""" amount = 0 def __init__(self, name, age, height): self.name = name self.age = age self.height = height Person.amount += 1 def __del__(self): Person.amount -= 1 def __str__(self): retur...
""" ******************************** * Print an empty box like this * ******************************** """ def boxPrint(symbol, width, height): if len(symbol) != 1: raise Exception('"symbol" needs to be a string of lenght 1.') if (width < 2) or (height < 2): raise Exception('"width" and "heog...
""" Generate fibonacci number based on a position """ def fibonacci1(num): """Non recursive function.""" first_value, second_value = 0, 1 for _ in range(num): first_value, second_value = second_value, first_value + second_value return first_value print(fibonacci1(6)) def fibonacci2(value): ...
import os def spec_athlete(c): athlete = input('Enter athlete name (partial name for search): ') if athlete == '': return c.execute('select distinct name, sport from athlete where name like ?', ('%' + athlete + '%',)) athletes = c.fetchall() athlete_cnt = len(athletes) if athlete_cnt > ...
import os import math import binascii import random # ref: https://qiita.com/srtk86/items/609737d50c9ef5f5dc59 def is_prime(n): if n == 2: return True if n == 1 or n & 1 == 0: return False d = (n - 1) >> 1 while d & 1 == 0: d >>= 1 for _ in range(100): a = random.ra...
# You will mainly encounter packing and unpacking in functions. # Double asterisks (**) on a parameter in Python will "pack" the keywords into a dictionary--hence, keyword arguments . . . kwargs def packer(**kwargs): print(kwargs) packer(name='Some_Name', num=777) # This will print {'name': 'Some_Name', 'num': 77...
def solution(numbers): answer = '' numbers = sorted( numbers, key=lambda x: str(x) * 4, reverse=True, ) for n in numbers: answer += str(n) return str(int(answer))
class Solution: # @param num, a list of integer # @return an integer def findMin(self, num): # 7 8 9 10 0 1 2 3 4 5 6 return helper(num,0,len(num)-1) def helper(num,left,right): if left == right: return num[right] mid = (right+left)//2 if num[mid]...
def life_path_number(birthdate): date = birthdate.split("-") year = date[0] month = date[1] day = date[2] res = sum_digits(year) + sum_digits(month) + sum_digits(day) return sum_digits(str(res)) def sum_digits(number): number = list(number) flag = True res = 0 while flag: res = sum([int(...
def sort_me(courses): data = list() for course in courses: temp = course.split("-") data.append(temp[1]+"-"+temp[0]) data = sorted(data) data_1 = list() for dato in data: temp = dato.split("-") data_1.append(temp[1]+"-"+temp[0]) return data_1 print(sort_me(...
class Private_Class(object): _name_class = "private class" _private = "private" def __init__(self): print("This is a private class") def __repr__(self): return f"Name class: {self._name_class} , Private: {self.__private}" object_private = Private_Class() print(object_private._private)
hello_msg = "Hello ! How are you ?" bye_msg = "Bye, Take Care" while True: user_message = input("Enter your message : ") user_message = user_message.lower() if user_message == "hi" or user_message == "hello" or user_message == "hey": print(hello_msg) elif user_message == "bye" or ...
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> hello_intent = ['hello','hi','hey','good morning','hie'] >>> word = "hello" >>> for w in hello_intent: if w == word: print("Match Found") print(w) ...
## Dynamic Arguments ## *args ## **kwargs def emp(id,name,age,*address): print("ID : {}".format(id)) print("Name : {}".format(name)) print("Age : {}".format(age)) #print("Address : {}".format(address)) for i,addr in enumerate(address): print("Address {} : {}".format(i+1,addr)) ...
# import logic # from logic import add # from logic import * import logic as calc num_1 = int(input("Enter first number : ")) num_2 = int(input("Enter second number : ")) result = calc.add(num_1, num_2) print(result)
import ast import csv '''Method for phrase extraction''' def phrase_extraction(srctext, trgtext, alignment): def extract(f_start, f_end, e_start, e_end): if f_end < 0: return {} for e,f in alignment: if ((f_start <= f <= f_end) and (e < e_start or e > e_end)): ...
""" Faça um programa que calcule o estoque medio de uma peça, sendo que: estoque medio = quantidade minima + quantidade maxima / 2 """ qtd_minima = int(input("Informe a quantidade minima da peça: ")) qtd_maxima = int(input("Informe a quantidade maxima da peça: ")) media_estoque = (qtd_minima + qtd_maxima) / 2 p...
# Faça um algoritimo que peça dois numeros e imprima a soma n1 = int(input("Informe o primeiro numero: ")) n2 = int(input("Informe o segundo numero: ")) soma = n1 + n2 print("A soma de {} + {} = {}".format(n1, n2, soma))
""" Construa um algoritmo que leia 10 valores inteiros e positivos e: a) Encontre o maior valor; b) Encontre o menor valor c) Calcule a média dos números lidos; """ x = 0 maior = 0 menor = 999 soma = 0 while x <= 10: n = int(input("Informe um numero positivo: ")) x += 1 soma += n if n > 0: if ...
""" Escreva um algoritmo que leia dois vetores de 10 posições e faça a soma dos elementos de mesmo índice, colocando o resultado em um terceiro vetor. Mostre o vetor resultante. """ v1 = [] v2 = [] soma = [] for n in range(1, 11): n1 = int(input("Informe o valor para o primeiro vetor:")) v1.append(n1) n2...
s=input("enter the string") l=[] j=[] for i in s: l.append(i) if(i.isdigit()==True): j.append(i) if(l==j): print("the string is numeric") else: print("the string is not numeric")
class Solution: """ @param nums: an array of n integers @param target: a target @return: the number of index triplets satisfy the condition nums[i] + nums[j] + nums[k] < target """ def threeSumSmaller(self, nums, target): # Write your code here if not nums: return 0 ...
class Solution: def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: i = 0 size = len(flowerbed) while i < size and n > 0: if flowerbed[i]: i += 2 continue if i == 0: if size == 1 or not flowerbed[i+1]: ...
class Solution: def canThreePartsEqualSum(self, A: List[int]) -> bool: part_sum = sum(A) // 3 i = 0 cur = 0 for _ in range(3): if i >= len(A): return False while i < len(A) and cur != part_sum: cur += A[i] i += 1...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def bstToGst(self, root: TreeNode) -> TreeNode: def helper(node, agg): if not node: return agg ...
#escreva um programa que leia um valor em metros e o exiba convertido em centimetros e milimetros valor = int(input('Informe o tamanho em metros:')) cm = valor * 100 mm = valor * 1000 print('Centimetro = {}cm \nMilimetro = {}mm'.format(cm, mm))
#faça um algoritimo que leia o preço de um produto e mostra seu novo preço, com 5% de desconto preco = float(input('Informe o valor do produto:')) desconto = preco - (preco * 5 / 100) print('Valor sem desconto {:.2f}\nValor com desconto {:.2f}'.format(preco, desconto))
import math class ship(): def __init__(self): self.x = 0 self.y = 0 self.ang = 0 def manhattan(self): return abs(self.y) + abs(self.x) def forward(self, dist): self.y += dist * round(math.sin(self.ang * math.pi / 180)) self.x += dist * round(math.cos(se...
def laceStrings(s1, s2): """ s1 and s2 are strings. Returns a new str with elements of s1 and s2 interlaced, beginning with s1. If strings are not of same length, then the extra elements should appear at the end. """ # Your Code Here minLen = min(len(s1), len(s2)) s3 = "".join(y f...
#Student ID:1201200637 #Student Name:Wee Chian Seong def main(): length=float(input("Enter Length :")); width=float(input("Enter Width :")); re=rectangle(length,width); te=triangle(length,width); print("Reactangle area : {:.2f}".format(re)); print("Triangle area : {:.2f}".format(te)); ...
#Student ID:1201200637 #Student Name:Wee Chian Seong def my_function(name,contact,salary,overtime): print("Hello",name); print("This is my phone number :",contact); total=float(salary)+ float(overtime) print("Your salary this month is RM {:.2f}".format(total)) my_function("Shawn Wee","1246",4...
""" Created on Wed Oct 13 09:24:05 2016 File: testBmi.py Date: 10/13/2016 Instructor: Nguyen Thai Course: CSC 7014 - The Practice of Computer Programming Author: Reshma Kapadnis Description: A program in which we create a test case to check the BMI class of the given list. """ from...
import numpy as np def matrix_multiply(A, B): rows_A = len(A) cols_A = len(A[0]) rows_B = len(B) cols_B = len(B[0]) if cols_A != rows_B: raise Exception("Incorrect dimensions to mutiply") # Create the result matrix # Dimensions would be rows_A x cols_B C = [[0 for row in range(cols_B)] for col in...
def is_x_more_dangerous_than_y(x, y, crazy_level): """This is a nonsense function. This is simple form: if crazy_level > 0: return x > y else: return not (x > y) """ x_danger = x y_danger = y exciting_level = abs(x - y) while exci...
# 1.Write a sample Python code to delete an element in a list? # 2. Write a sample Python code to return a value in a tuple? aList = ["Write", "sample", "Python", "code"] aList.remove('Python') # The differences between tuples and lists are, the tuples cannot be changed # unlike lists and tuples use parentheses, wher...
''' Real Python 7.7 Simulate Events and Calculate Probabilities    ''' from random import randint ''' Review exercice 1 Write a script that uses the randint() function to simulate the toss of a die, returning a random number between 1 and 6.  #Simulate the toss of a die print("Your die roll is {}".forma...
''' Real Python     7.8 assignment simulate an election     Simulate an election between two candidates, A and B. One of the candidates wins the overall election by a majority based on the outcomes of three regional elections. (In other words, a candidate wins the overall election by winning at least two regional elect...
''' Real Python 3.3 Assignment: pick apart your user's input ''' input_password = input("Tell me your password please : ") first_letter = input_password[0:1].upper() print('Your password begins with', first_letter, 'and is', len(input_password), 'long')
''' Real Python Chapter 15.1 Let's get some practice with how to handle file dialogs by writing a simple, usable program. We will guide the user (with GUI elements) through the process of opening a PDF file, rotating its pages in some way, and then saving the rotated file as a new PDF ''' ### Module(s) importation ###...
# This is my first python script ''' je vais faire deux lignes de commentaires parce que j'ai envie de parler''' phrase = "Hello, world" phrasebis = "Good morning" #print(phrase, phrasebis) # concatenation de deux variables """ pour un résultat impressionnant """ long_string_2_re_3 = """ ma super longue chai...
def gen_batches(n, batch_size): """Generator to create slices containing batch_size elements, from 0 to n. The last slice may contain less than batch_size elements, when batch_size does not divide n. Examples -------- >>> from sklearn.utils import gen_batches >>> list(gen_batches(7, 3)) ...
loop='Y' a=[] while(loop=='Y'): nij=input() k1=int(nij.split(' ')[0]) k2=int(nij.split(" ")[1]) a.append(k2-k1) print(k1,k2) loop=input("Y or N") for x in a: print(x)
x=int(input("c")) if(x=0) print("zero"): elif(x>0): print(positive") else: print(negative")
class Monster: def __init__(self,level): self.level=level self.set_health(level) self.set_power(level) # give moster health point based on their level if level is string will raise an error def set_health(self,value): if type(value) is str: raise Attri...
""" Custom exception classes. These vary in use case from "we needed a specific data structure layout in exceptions used for message-passing" to simply "we needed to express an error condition in a way easily told apart from other, truly unexpected errors". """ from collections import namedtuple from traceback import...
#python3 -m pip install RPi.GPIO import RPi.GPIO as GPIO from time import sleep import os GPIO.setmode(GPIO.BCM) sleepTime=0.1 lightPin=4 buttonPin=17 GPIO.setup(lightPin,GPIO.OUT) GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.output(lightPin,False) try: while True: #lights up light on press an...
a=input("Enter the number of elements in an array:") msg_array=list() print("Enter the elements to be added:") for i in range(int(a)): n=raw_input() msg_array.append(int(n)) for r in range(2,a): Total=sum(msg_array) print(Total)
string="hari" n=int(input("enter a number")) for i in range(1,n+1): print(string)
n=int(input("Enter the number of elements in an array:")) Total=0 msg_array=list() for i in range(0,n): n=raw_input() msg_array.append(int(n)) k=int(input("Enter the elements to be added:")) if(n>k): for i in range(0,k): Total=Total+msg_array[i] print(Total) else: print("not valid")
import os def search(default_path): file_list = [] for (path,dir,files) in os.walk(default_path): for filename in files: file_list.append(path+"\\"+filename) return file_list
from tkinter import * import menu_item import category import menu class MenuGUI: def __init__(self): """Constructor method for the GUI""" self.__window = Tk() #Create main window self.__frame = Frame(self.__window, bg="black") self.__menu_frame = Frame(self.__frame, bg="black") #Create menu frame ...
# List is the type of datatype where U can store multiple value # It is inserted in [] brackets For eg. # List is imutable -- Means It can not change Items_grocery = ["choclate","candy","toffee","shirt","cell",] print(Items_grocery[0]) #U can print them using print(Listname[Item_order]) #It can Store Intergers also ...
from tkinter import Tk, Button, Entry, Text, END, StringVar window=Tk() def km_to_miles(): miles=float(e1_value.get())*1.62 t1.insert(END, miles) b1 = Button(window, text="Execute", command=km_to_miles) b1.grid(row=0, column=0) e1_value = StringVar() e1 = Entry(window, textvariable=e1_value) e1.grid(row=0, ...
#!/usr/bin/env python import sys from random import choice from itertools import product import argparse def parse_arguments(): ''' parse the arguments ''' p = argparse.ArgumentParser() p.add_argument('--words-file', help='file with list of words [/usr/share/dict/words]', ...
#Write your function here def combine_sort(lst1, lst2): new_lst = lst1 + lst2 new_lst.sort() return new_lst #Uncomment the line below when your function is done #should return [-10, 2, 2, 4, 5, 5, 10, 10] print(combine_sort([4, 10, 2, 5], [-10, 2, 5, 10])) #shoudl return [-1, 1] print(combine_sort([1],...
# Write your remainder function here: def remainder(num1,num2): return (num1 * 2) % (num2 * 0.5) # Uncomment these function calls to test your remainder function: print(remainder(15, 14)) # should print 2 print(remainder(9, 6)) # should print 0
#Data Types #Strings message = "My car is : " message_2 = 'My car is : ' apple = "apple" one = "1" #print(one + "happy" + one) #Numbers total = 1 + 1 - 1 * 1 / 1 #print(total) #PLease excuse my dear aunt sally #(), ^2, *, /, +, - total = (1*1) - (1/1) #print(total) total_two = 98340238409238432084 * 78237492387...
from math import pi,cos,sin,sqrt from random import seed,random from functools import reduce import time def randomFirst(n, left, right): points = [] seed(1) for i in range(0,n): points.append((left+random()*(right-left),left+random()*(right-left))) return points def randomSecond(n, ...
from hand import Hand import copy import collections from dealer_player import DealerPlayer Player = collections.namedtuple('Player', ['player_obj', 'hand', 'bank']) class Dealer(DealerPlayer): def __init__(self, deck): self._deck = deck self._dealer = NotImplemented # todo: what is this suppos...
#Complex Data Types my_list = [1,2,3] #list elements can be anything! mixed_list = ["A",5.7,3,my_list] #list comprehension original_list = [1,2,3,4,5,6,7,8] squares = [x*x for x in original_list] #selection of lists first3 = squares[0:2] #strings and lists letters = "ABC DEF" #gives [ABC, DEF] ...
# задание 5 prices_string = '' prices_list = [57.8, 46.51, 97, 126.50, 13.80, 16, 123.5, 11.25, 67.40, 25.89, 234.56, 65.95] for i in prices_list: num_1 = int(i // 1) # кол-во рублей num_2 = int(i % 1 * 100) # кол-во копеек prices_string = prices_string + f'{num_1} руб {num_2:02} коп, ' # в задании вы...
def thesaurus(*names): workers_by_letter = {} for name in names: if name[0] in workers_by_letter: workers_by_letter[name[0]].append(name) else: workers_by_letter[name[0]] = [name] return workers_by_letter print(thesaurus('Иван', 'Мария', 'Петр', 'Илья'))
from _operator import inv ''' data importion and pre-analysis ''' import numpy as np # for matrix calculation import matplotlib.pyplot as plt # load the CSV file as a numpy matrix data_file = open('../data/watermelon_3a.csv') dataset = np.loadtxt(data_file, delimiter=",") # separate the data from the target attribu...
import math import numpy as np def basic_sigmoid(x): s = 1 / (1 + math.exp(-x)) return s print(basic_sigmoid(3)) #np.exp x = np.array([1, 2, 3]) print(np.exp(x)) print(x + 3) def sigmoid(x): s = 1 / (1 + np.exp(-x)) return s x = np.array([1, 2, 3]) print(sigmoid(x))
#int () - создает целое число из целочисленного литерала, литерала с плавающей запятой (путем удаления всех десятичных знаков) # или строкового литерала (при условии, что строка представляет собой целое число) #float () - создает число с плавающей запятой из целочисленного литерала, # литерала с плавающей запятой или ...
#Примечание. Python не имеет встроенной поддержки массивов, но вместо них можно использовать списки Python . #Массивы #Примечание. На этой странице показано, как использовать СПИСКИ как Массивы, # однако для работы с массивами в Python вам придется импортировать библиотеку, # например библиотеку NumPy .# #Массивы и...
class Human: type = "humnan" def __init__(self,name, gender): self.gender = gender self.name = name def move(self): print("A human is moving") def sleep(self): print("A human is sleeping") class Character(Human): type = "anime" def __init__(self,name, maho...
sayi = (input("Lutfen pozitif bir tam sayi giriniz:")) us = len(sayi) sayac = 0 if not sayi.isdigit() : print(sayi, "It is an invalid entry. Don't use non-numeric, float, or negative values!") elif int(sayi) >= 0: for i in range(us): sayac += int(sayi[i]) ** us if sayac == int(sayi): print(s...
import math def Mean(List): Sum=0 for i in range(0,4): Sum=Sum+List[i] return Sum/4 def Variance(List): Sum=0 MeanVal=Mean(List) for i in range(0,4): Sum=Sum+pow(List[i]-MeanVal,2) return Sum/4 def STDev(List): return math.sqrt(Variance(List)) def Interval(List): ...
import unittest from has22 import has22 class UnitTests(unittest.TestCase): def test_1_2_2_returns_true(self): actual = has22([1, 2, 2]) expected = True self.assertEqual( actual, expected, 'Expected calling has22() with [1, 2, 2] to return "True"') def test_1_2_1_2_return...
from deck_of_cards import Card, Deck import unittest class CardTests(unittest.TestCase): # This "setUp" runs before each test method def setUp(self): self.card = Card("J", "Spades") # Checks to see if the card has a suit and a value def test_init(self): """Cards should have a ...
import unittest from combo_string import combo_string class UnitTests(unittest.TestCase): def test_hello_and_hi_returns_hihellohi(self): actual = combo_string("Hello", "hi") expected = "hiHellohi" self.assertEqual( actual, expected, 'Expected calling combo_string() with "Hello...