text
stringlengths
5
121k
""" Created on Tue Dec 3 19:18:03 2019 @author: Anthony Pitts, anthony.pitts@columbia.edu Description: Searches a tree for a specfified node name """ class Node: Name = None Children = [] def __init__(self, name = "", children = []): self.Name = name ...
str = 'python quiz practice code' def opstr (a): lis = "" c = a.split() b = len(c) - 1 lis = lis + c[b] while b > 0: lis = lis + " " + c[b - 1] b = b - 1 return lis print (opstr(str))
correctlis = [5,7,12,50] wronglis = [5,2,3,1,5000] def orglist (a): length = len(a) i = 0 b = 1 flag = True while i < (length - 1) : b = i + 1 if a[i] > a[b]: flag = False break i = i+1 return flag g = orglist(correctlis) f = orglist(wronglis) p...
a = 'Hello, World' print(a[1:2])
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", password="" ) print(mydb) mycursor = mydb.cursor() mydb = mysql.connector.connect( host="localhost", user="root", password="", database="mydatabase" ) mycursor = mydb.cursor() ...
import statistics import numpy as np list = [] n = int(input("masukan jumlah data :")) for i in range(0, n): nilai = int(input()) list.append(nilai) list.sort() average = statistics.mean(list) median = statistics.median(list) modus = statistics.mode(list) print("Nilai Rata-Rata :",average) print("Medi...
""" Implementation of deep search in a binary tree. In this search approch, we use a stack to organize the elements to be covered. Therefore, we did not use a explicit stack, instead we use the implict function call stack. """ import numpy as np find = 0 class node(): def __init__(self, value=None): self.val...
''' client_datatypes.py This file contains the basic data types that hold the various expected inputs from the Super Street Fire game sensors @author: Callum Hay ''' import operator PLAYER_ONE = 1 PLAYER_TWO = 2 class GloveData: NUM_GLOVE_DATA = 9 LEFT_HAND_GLOVE = ...
import matplotlib.pyplot as plt import morphdetect.loging as log def visualize_2D_binary_matrix(binary_matrix: list): """Visualizes a given 2D Matrix which stores only binary values""" log.log_info( str(visualize_2D_binary_matrix.__name__) + ": visualize matrix with height: " + str(len(binary_matrix))...
import traceback while True: print("...") try: s = input(">") i = int(s) if i == 0: raise ValueError("i don't be zero") assert i > 0, f"{i} less by zero" except ValueError as err: print(f"error: {str(err)}: " + err.args[0]) except KeyboardInterrup...
""" Created on Wed Jan 11 22:42:20 2017 @author: Alexandre Sales Lima Cursos de Big Data & Data Science Trabalho 1 Questão 2 """ import numpy as np def fibonacci(n): if n == 0: return print( 0) elif n == 1: return print( 1 ) f = np.zeros(n,dtype = int) ...
class Solution(object): def canJump(self, nums): nums_len = len(nums) result_arr = [False] * nums_len result_arr[0] = True current_true_i = 0 for i in range(nums_len): if nums[i] >= 1 and result_arr[i]: if i+nums[i] > current...
import gettext import random import sys def tr(text): return gettext.gettext(text) def pl(text, textpl,count): return gettext.ngettext(text,textpl,count) class Animal: def __init__(self,name, name_plural,number_of_legs): self.name = name self.name_plural = name_plural self.numbe...
import sys raise_applied=6 raise_desired=40 salary_now=100 desired_salary=salary_now*(1+raise_desired/100.0) year_count=0 money_lost=0 while salary_now < desired_salary: year_count+=1 salary_now=salary_now*(1+raise_applied/100.0) money_lost += (desired_salary-salary_now)*12.0 print(...
stmt = True contradiction = False if(stmt): print("Indeed!") if(contradiction): print("Still true, but shouldn't be! Wtf?") else: print("I'm afraid I'm obliged to protest!") print("------- WHILE LOOP ---------") number = 0 while(number < 5): print("Nr is %s" %number) number = num...
import sys import pygame from pygame.locals import * pygame.init() pygame.display.set_caption('game base') screen = pygame.display.set_mode((500, 500), 0, 32) clock = pygame.time.Clock() pygame.joystick.init() joysticks = [pygame.joystick.Joystick(i) for i in range(pygame.joystick.get_count())] for joystick in...
T = int(input("tal: ")) def delfem(a): if a % 5 == 0: return True else: return False print(delfem(T))
def insertionSort(array): for i in range(len(array)): j=i-1 while array[j] > array[j+1] and j >=0: array[j], array[j+1] = array[j+1], array[j] j -= 1 return array print(insertionSort([1,5,8,2,9,0]))
import simple_draw as sd sd.resolution = (1200, 600) def brick(x, y): left_bottom = sd.get_point(x, y) right_top = sd.get_point(x + 100, y + 50) sd.rectangle(left_bottom, right_top, width=5) start_x = -25 for y in range(0, 600, 50): for x in range(start_x-25, 1200, 100): brick(x...
numbers = ['0','1','2','3','4','5','6','7','8','9'] with open('input.txt', 'r') as input_file, open('output.txt', 'w') as output_file: for line in input_file: count = '' symbol = line[0] for i in range(1, len(line)): if line[i] not in numbers: output_file.write(s...
print("Calcule a area de um retangulo") base = input("Qual o tamanho da base do seu retangulo? ") altura = input("Qual o tamanho da altura do seu retangulo? ") area = float(base) * float(altura) print(f'O seu retangulo possui area: {area} unidades de metida')
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: length = 0 p = head while p: length += 1 p = p.next del_index = length - n ...
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1, l2): sum_val = l1.val + l2.val p = l3 = ListNode(int(sum_val % 10)) left = int(sum_val / 10) l1 = l1.next l2 = l2.next while l1 and l...
from copy import copy,deepcopy def copy_tutorial(): ''' 第一层的id不一样,但是第二层的id是一样的,指向的是同一块地址 修改copy1,就会修改copy2 ''' dict_in = {"name":"Cary","favor":["tabletennis","basketball"]} dict_copy1 = copy(dict_in) dict_copy2 = copy(dict_in) print("Before copy1:{}".format(dict_copy1)) print("Befor...
test_cases=int(input("Enter Number of Test Cases:")) def split(word): return [char for char in word] for i in range (0,test_cases,1): N = int(input()) if N%2 == 0: print("Input is incorrect") in_string_temp = str(input()) in_string = split(in_string_temp) a_value = 0 b_value = 0 ...
""" 四则运算 """ def show_nenu(): cmd_menu = ("\n" "[1] Add\n" "[2] Subtract\n" "[3] Multiply\n" "[4] Divide\n") print(cmd_menu) return def calc(num1, num2, opt): if opt == 1: return num1 + num2 elif opt == 2: retur...
import pygame,sys from pygame.locals import * pygame.init(); windows_surface = pygame.display.set_mode((10,10), pygame.NOFRAME); x,y =0,0; while True: for event in pygame.event.get(): if event.type==KEYDOWN: if event.key==K_LEFT: x-=1 print(x,y) if event.key==K_...
def new_in_list(my_list, idx, element): new_list = my_list.copy() if idx < 0: return new_list i = 0 for x in new_list: if i == idx: new_list[idx] = element i += 1 return new_list
""" In this file a main for add arguments to a Python list and save them in a file """ from sys import argv load_from_json_file = __import__('6-load_from_json_file').load_from_json_file save_to_json_file = __import__('5-save_to_json_file').save_to_json_file if __name__ == "__main__": filename = "add_item.json" ...
celsius=input('Enter a temperature in degrees Celsius: ') fahrenheit=9/5*(float(celsius))+32 print('The temperature in degrees Fahrenheit is ', fahrenheit)
inp=input('Enter a string:\n') index=len(inp)-1 while index >=0: letter=inp[index] print(letter) index=index-1
fname=input('Enter the file name: ') try: fhand=open(fname) except: print('File cannot be opened:', fname) exit() count=0 total=0 for line in fhand: if line.startswith('X-DSPAM-Confidence:'): count=count+1 atpos=line.find(':') num=float(line[atpos+1:-1]) total=total+num average=total/count print('Ave...
statse = { 'Oregon': 'OR', 'Floida': 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI' } cites = { 'CA': 'san Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville' } cites['NY'] = 'New york' cites['OR'] = 'Oregon' print('-' * 10 * 10) print("Michigan's abbreviation is...
students = [ {'first_name': 'Michael', 'last_name': 'Jordan'}, {'first_name': 'John', 'last_name': 'Rosales'}, {'first_name': 'Mark', 'last_name': 'Guillen'}, {'first_name': 'KB', 'last_name': 'Tonel'} ] def iterate_dictionary(some_list): for x in some_list: ...
def changeVal(x): x += 100 n = 10 print(n) changeVal(n) print(n) print("Example 1") def changeList_1(l): l.append(50) myList_1 = [10,20,30,40] print(myList_1) changeList_1(myList_1) print(myList_1) print("Example 2") def changeList_2(l): l = [] l.append(50) print...
print("******** first Example") grades = [95.5, 98.5, 86, 79, 65] modifiedGrades = [] for grade in grades: modifiedGrades.append(grade + 1.5) print(grades) print(modifiedGrades) modifyGrades = [grade + 2.5 for grade in grades] print(modifyGrades) print("******** second Example")...
""" def squence_num(nums): result = [] for i in nums: result.append(i*i) return result squared_list = squence_num([1,2,3,4,5]) print(squared_list) """ def squence_num(nums): for i in nums: yield(i*i) """ print(squared_list) print(next(squared_list)) prin...
class TicTacToe: def __init__(self, inp_board=[[0, 0, 0], [0, 0, 0], [0, 0, 0]]): self.board = inp_board def getDiag(self): board = self.board diag1 = [] diag2 = [] for i in range(3): for j in range(3): diag1.append(board[i][j]) ...
import random name = 'Ryan' rand_one = random.randint(0,100) rand_two = random.randint(0,100) rand_sum = rand_one + rand_two print(name) print(rand_one) print(rand_two) print('Sum = {}'.format(rand_sum)) print('Average = {}'.format(rand_sum / 2.0))
import re numberRegex=re.compile(r'''((\d\d)(\d)*)* #AREA CODE (-)?( )? #SEPARATOR (\d\d\d)(\d)? # 3 OR 4 DIGITS (-)?( )? #SEPARATOR (\d\d\d\d) # 4 DIGITS ''',re.VERBOSE) phoneNum=numberRegex.search('010-2622-4540') if phoneNum==None: print('wrong number') else: print(phoneNum.group())
import random for i in range(5): print(random.randint(1,10))
def print_line(): for i in range(10): print("_", end="") print() for i in range(10): print_line() """ \n - new line character \t - tab https://www.w3schools.com/python/gloss_python_escape_characters.asp """
first = "10" second = "10" print(first + second) a = 10 b = 10 print(a + b)
numbers = [33, 55, 6, 77, 8, 9] print(numbers) numbers.sort() print(numbers) cities = ["Hyderabad", "Chennai", "Bengaluru", "Mumbai"] cities.sort() print(cities) """ Sorting Techniques, suggested reads bubble sort selection sort insertion sort merge sort quick sort radix sort .... ...... """
def print_sum(num): sum = (num * (num+1)) / 2 print(f"Sum of first {num} Natural numbers = {sum}") def main(): n = int(input("Enter n: ")) print_sum(n) main()
import pandas as pd from datetime import datetime as dt class Item: def __init__(self,item_code,item_name,price): self.item_code=item_code self.item_name=item_name self.price=price def get_price(self): return self.price class Order: def __init__(self,item_master): ...
q = 459 p = 0.098 print(q, p, p * q) print(q, p, p * q, sep=",") print(q, p, p * q, sep=":") print(str(q) + " " + str(p) + " " + str(p * q)) print("Art: %5d, Price per Unit: %8.2f" % (453, 59.058)) print('I am using %s %d.%d' % ('Python', 3, 2)) ''' Format specification b : Binary format. Outputs the n...
HEIGHT = 15 WIDTH = 15 board = [[[] for y in range(HEIGHT)] for x in range(WIDTH)] for i in range (0, HEIGHT): for j in range (0, WIDTH): board[i][j] = 0 def printBoard(WIDTH,HEIGHT): print("") print("+" + "---+" * WIDTH) for rowNum in range(HEIGHT - 1, -1, -1): row = "|" ...
""" info about our project """ __author__ = "Fre Van Buynder" __email__ = "fre.vanbuynder@student.kdg.be" __status__ = "Development" def main(): list_of_words = ["hi", "I", "am", "Fre", "how", "are", "You"] searching_word = input("Which word do you want to find?: ") i = 0 while i < len(list_o...
""" info about project """ __author__ = "Fre Van Buynder" __email__ = "fre.vanbuynder@student.kdg.be" __status__ = "Development" def main(): word = input("Give me a random word (the more random the better): ") print("the word exist of", len(word), "letters") if __name__ == '__main__': main()
word=input() w_len=len(word) list=[] for j in range(26): list.append(0) for i in range(w_len): list[ord(word[i])-97]+=1 for k in range(26): print(f"{list[k]} ",end='')
def max(n1,n2): div=0 for i in range(1,(n2 if n1>n2 else n1)+1): if(n1%i==0 and n2%i==0): div=i return div def min(n1,n2): n1d=n1/max(n1,n2) n2d=n2/max(n1,n2) return max(n1,n2)*n1d*n2d def main(): num1, num2=input().split( ) num1=eval(num1) num2=eval(num2) pri...
def multiplication_table(row,col): results = [] for i in range(1, row + 1): tmp = [] for j in range(1, col + 1): if i != 1: tmp.append((results[0][j - 1] * i )) else: tmp.append(j) results.append(tmp) return results
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 4: The telephone company want to i...
ciphertext = input("Enter ciphertext: ") plaintext = "" for a, b, c in zip(ciphertext[0::3], ciphertext[1::3], ciphertext[2::3]): plaintext += c + a + b print() print(plaintext)
text = list(input().split()) for i in range(len(text)): text[i] = int(text[i], 2) text[i] = chr(text[i]) print(text[i], end='')
brackets = input() opening = '([{' closing = ')]}' flag = True if brackets[0] == closing[0] or brackets[0] == closing[1] or brackets[0] == closing[2] or brackets[-1] == opening[0] or brackets[-1] == opening[1] or brackets[-1] == opening[2]: flag = False elif len(brackets) % 2 != 0: flag = False else: op, c...
def main(): num = float(input('enter a number:')) if num > 0: print('the num is positive') elif num == 0: print('the num is zero') else: print('the num is negative') if __name__ == "__main__": main()
import math def shortest_path(data, start, end, has_sword): unexplored = [start] explored = set() steps = 0 rows = data["size"] columns = data["size"] if unexplored == []: return None if start == end: return steps ...
'''program demonstrating continue statement ''' list1 = ['tomato', 'potato', 'onion', 'biscuits'] for i in list1: if i == 'onion': continue print(i)
def call_1000_times(count): if count == 1000: return True else: return call_1000_times(count + 1) call_1000_times(10000)
from Bio import SeqIO from Bio.SeqUtils import GC GCcont=0 GCseq="" file=open("rosalind_GC.txt", "r") for record in SeqIO.parse(file, "fasta"): if GCcont < GC(record.seq): GCcont = GC(record.seq) GCseq = record.id print(GCseq,round(GCcont,2),"%")
import re def build_match_and_apply_functions(pattern, search, replace): def matches_rule(word): return re.search(pattern, word) def apply_rule(word): return re.sub(search, replace, word) return (matches_rule, apply_rule) patterns = \ ( ('[sxz]$', '$', 'es'), ('[^a...
X1=float(input("Ingrese X1:")) Y1=float(input("Ingrese Y1:")) X2=float(input("Ingrese X2:")) Y2=float(input("Ingrese Y2:")) D=((X1-X2)**2+(Y1-Y2)**2)**0.5 print(f"La distancia entre los puntos ({X1},{Y1}) y ({X2},{Y2}) es: {D}")
NOMINA=0 for i in range (1,11,1): SUE=float(input("Ingrese el sueldo:")) NOMINA += SUE print("La nomina de la empresa es:", NOMINA)
CAT=int(input("Introdusca la categoria del trabajador (1-4):")) SUE=float(input("Introdusca el sueldo del trabajador:")) NSUE=0 if CAT ==1: NSUE=SUE*1.15 elif CAT==2: NSUE=SUE*1.10 elif CAT==3: NSUE=SUE*1.08 elif CAT==4: NSUE=SUE*1.07 print(f"El sueldo con categoria {CAT} con el aumento es: {NSUE}")
A=int(input("Ingrese un numero entero para A:")) if A==0: print(f"El numero es nulo {A}") elif (-1**A)>0: print(f"El numero {A} es par") else: print(f"El numero {A} es impar") print("Fin")
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns df = pd.read_csv('TensorFlow_FILES/DATA/fake_reg.csv') df.head() sns.pairplot(df) plt.show() from sklearn.model_selection import train_test_split X = df[['feature1', 'feature2']].v...
BRICK = "o" CHK = "x" SPACE = " " NEWLINE = "\n" LEVEL = 1 GV=0 L=1 R="r" var_fill=0 total=0 def percentage(numerator, denominator): temp1 = float(numerator)*100 temp2 = float(denominator) fin = temp1/temp2 fin2 = math.ceil(fin*100) return fin2/100 def brickfunction(jk): matrixvar = 50 ...
def printPrimeFactors(num): ''' prints primeFactors of num :argument: number whose prime factors need to be printed :return: ''' for i in range(2, num+1): if isPrime(i) and num%i==0: print(i) def isPrime(num): ''' Checks if num is prime or not :param num: :r...
from collections import namedtuple Bracket = namedtuple("Bracket", ["char", "position"]) def are_matching(left, right): return (left + right) in ["()", "[]", "{}"] def find_mismatch(text): stack = [] for i, char in enumerate(text, start=1): if char in "([{": stack.append((char, i)) ...
first_name = input("Please input your first name: ") last_name = input("Please input your last name: ") print("Hello "+last_name+" "+first_name+ ".How are you?")
import random while(True): print("수를 결정하였습니다. 맞추어 보세요") correct = round(random.random()*99 + 1) higher = 1 lower = 100 answer = -1 count = 1 while(answer != correct): print(higher, '-', lower, sep='') answer = int(input(str(count)+'>>')) if answer > correct: ...
def get_indices_of_item_weights(weights, length, limit): """ YOUR CODE HERE """ h = {} packages = None for n in weights: h[n] = limit - n if len(weights) == 2 and weights[0] + weights[1] == limit: packages = (1, 0) return packages ...
import time def f(n): if n == 1: return 1 if n ==2: return 2 if n > 2: return f(n - 1) + f(n - 2) s1 = f(100) print("s1=",s1) def f(n): res = [0 for i in range(n+1)] res[1] = 1 res[2] = 2 for i in range(3, n+1): res[i] = res[i - 1] + res[i -2] re...
from abc import ABC, abstractmethod from typing import Iterable from structures.linked_list_extra import LinkedList class _Linear(ABC): """Abstract linear data structure.""" def __init__(self, items: Iterable = None): self._items = LinkedList(items) def push(self, item): """Adds one item...
import sys input = sys.stdin.readline class Node: child = {} def __init__(self): self.child = {"" : None} def setChild(node, c): node.child[c] = Node() class TrieTree: node = Node def __init__(self): self.node = Node() def insert(self, key): node = s...
A = input() ans = [] for char in A: ans.append('a') if ans[:-1]: print(''.join(ans[:-1])) elif A[0] > 'a': print(ans[0]) else: print(-1)
import sys input = sys.stdin.readline def binarySearch(S, N, t): N = N // 2 if S[N] == None: return 0 else: return binarySearch(S[:N], N, t) + binarySearch(S[N+1:], N, t) return N = int(input()) S = input().strip().split() S.prepend(None) S.append(None) Q = int(input...
from typing import List def appendOnSameLevel(t, level, depth): if t == None: return if len(level) < depth: level.append([]) level[depth-1].append(t.val) appendOnSameLevel(t.left, level, depth+1) appendOnSameLevel(t.right, level, depth+1) return class Sol...
import random def decoCheckNumber(func): print ('Inside the decorator') def xyz(): print('*************** Inside xyz *********************') num = func() print(num) if num %2 != 0: print('number is odd') else: print('number is Even') return...
class Node: def __init__(self, value): self.info = value self.next = None class LinkList: def __init__(self): self.start = None def create_list(self, li): if self.start is None: self.start = Node(li[0]) p = self.start for i in range(1,len(li)): temp = ...
""" https://leetcode.com/problems/find-minimum-in-rotated-sorted-array Complexity ---------- O(logn) """ class Solution: def findMin(self, nums): l = 0 h = len(nums) - 1 while l < h: m = (l + h)//2 if nums[m] <= nums[h]: h = m else: l = m + 1 return nums[l] def mai...
class X: def who_am_i(self): print("I am a X") class Y: def who_am_i(self): print("I am a Y") class A(X, Y): def who_am_i(self): print("I am a A") class B(Y, X): def who_am_i(self): print("I am a B") class F (A, B): def who_am_i(self): print(...
def bubble_sort(un_list): n = len(un_list) for i in range(n): for j in range(n-1-i): if un_list[j] > un_list[j+1]: un_list[j+1], un_list[j] = un_list[j], un_list[j+1] def main(): unsorted_list = [8, 5, 6, 9, 1, 4, 10, 3, 2, 7] print('************ UNSORTED LIST **************'...
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ if x > 2**31 - 1 or x <= -2**31: return 0 num1 = x sum = 0 if x < 0: x = x *-1 while(x): sum = sum * 10 rem = x...
class A(object): a = 1 def __init__(self, n = 'Rahul'): print('A') self.name = n class B(A): def __init__(self, roll): print('B') self.roll = roll super...
""" https://leetcode.com/problems/add-two-numbers/ Complexity ---------- O(max(m, n)) time and space """ class ListNode: def __init__(self, x): self.val = x self.next = None class LinkList: def __init__(self): self.start = None def create_list(self, li): if self.start is None: self.star...
class Node: def __init__(self, value): self.info = value self.next = None class SingleLinkList: def __init__(self): self.start = None def create_list(self, li): if self.start is None: self.start = Node(li[0]) p = self.start for i in range(1,len(li)): temp = Node(li[i]) ...
class Node: def __init__(self, value): self.info = value self.next = None class LinkList: def __init__(self): self.start = None def create_list(self, li): if self.start is None: self.start = Node(li[0]) p = self.start for i in range(1,len(li)): temp = Node(li[i...
def decoWrapper1(func): def xyz(): print('start') func() return xyz @decoWrapper1 def print_hello1(): print('Hello') print('***************** decorator with function only ********************') print_hello1() def decoWrapper2(func): def xyz(arg): print('start', arg) ...
class Solution: def romanToInt(self, s: str) -> int: if not s: return 0 switcher = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000 } switcherSubs = { 'IV': 4...
from functools import partial def power(base, expo): print('{} base to the power of {}'.format(base, expo)) return base ** expo square = partial(power, expo=2) cube = partial(power, expo=3) print(square(3)) print(cube(3))
import copy l1 = [[1,2], 3, 4, [5, 6, 7]] l2 = copy.copy(l1) l2[0][0] = 8 print('************** SHALLOW COPY **************') print(l1) print(l2) l2[1] = 12 print(l1) print(l2) l3 = [[1,2], 3, 4, [5, 6, 7]] l4 = copy.deepcopy(l1) l4[0][0] = 8 print('**************** DEEP COPY ***************') print(l3) print...
''' In the previous Urban Planner exercise, you practices defining custom types to represent buildings. Now you need to create a type to represent your city. Here are the requirements for the class. You define the properties and methods. Name of the city. The mayor of the city. Year the city was established. A collect...
def alphabet_position(letter): alphabet = 'abcdefghijklmnopqrstuvwxyz' alphabet2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' if letter.isupper(): position = alphabet2.index(letter) else: position = alphabet.index(letter) return(position) def rotate_char(char, rot): alphabet = 'abcdefghijklm...
my_dictionary = { "some_key": "some value" } my_dictionary['some_key'] class User: def __init__(self, name): self.name = name def greet(self): print(f'Hi my name is {self.name}') me = User('Michael') bob = User('Bob') sally = User('Sally') me.greet() print(me) print(me.name) class B...
ASCII = input("Please enter ASCII value: ") if ASCII.isnumeric(): if int(ASCII) > 0 and int(ASCII) < 127: input_ASCII = int(ASCII) print("The character is", chr(input_ASCII), ".") else: print("Invalid option!") ASCII = input("Please enter ASCII value:") if ASCII.isn...
import Addition def meanCalculation(listofnum): ans = 0.0 for elem in listofnum: ans += elem return ans/len(listofnum) def mean(listofnumbers): return (meanCalculation(listofnumbers))
def is_armstrong(number): return sum(list(map(lambda i: i ** len(str(number)), [ int(elem) for elem in str(number)]))) == number if __name__ == '__main__': assert is_armstrong(153) is True, 'Число Армстронга' assert is_armstrong(10) is False, 'Не число Армстронга'