text
stringlengths
37
1.41M
#Make the factorial function def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) #Print the answer print("5! is equal to", factorial(5)) #5! is 5 x 4 x 3 x 2 x 1 #More infomation on how to do this at https://en.wikipedia.org/wiki/Factorial
def power(*args): lista = [] i = 0 n = 1 for a in args: lista.append(a) if len(lista) == 2: p = lista[1] else: p = 2 while i < p: n *= lista[0] i += 1 return n def main(): print(power(3, 9)) if __name__ == "__main__": m...
grados = int(input("Introduce la Tª en ºF: ")) grados = (grados - 32) * 5 / 9 print("La temperatura en ºC es", grados)
import string texto = input("Introduzca un texto: ") i = 0 for char in texto: if char in string.ascii_uppercase: i += 1 print("Hay {} mayusculas".format(i))
# Enter your code here. Read input from STDIN. Print output to STDOUT import sys import xml.etree.ElementTree as etree raw_input() xml = sys.stdin.read() # print xml tree = etree.ElementTree(etree.fromstring(xml)) print sum(map(lambda x: len(x.attrib), tree.iter()))
# -*- coding: utf-8 -*- import string # --- part one --- def parse_inputs(file): with open(file, "r") as f: return f.readline().rstrip() polymer = parse_inputs("input.txt") def lower_upper(): lower_upper = {} for letter in string.ascii_lowercase: lower_upper[letter.lower()] = letter...
# TO FIND THE AREA OF CIRCLE pi = 3.14 r = float(input("Enter The Radius Of Circle")) a = pi * r * r print("\n The Area Of Circle Is = ", a)
''' TO FIND GROSS SALARY BY GETTING BASIC SALARY AS INPUT FROM USER BASIC SALARY < 25000 : HRA = 20% ; DA = 80% BASIC SALARY >= 25000 : HRA = 25% ; DA = 90% BASIC SALARY >= 40000 : HRA = 30% ; DA = 95%''' basic = float(input("Enter Basic Salary Of Employee")) if(basic<25000): da = basic * 8...
''' @judge ZeroJudge @id c014 @name Primary Arithmetic @source UVa 10035 @tag Ad-hoc, Binary Operations ''' from sys import stdin def carrying(a, b): ans = 0 c = 0 while a != 0 or b != 0: c = 1 if a % 10 + b % 10 + c >= 10 else 0 ans += c a //= 10 b //= 10 return ans def solve(): for line in stdin...
''' @judge CodeForces @id 1097A @name Gennady and a Card Game @tag Ad-hoc, Card Game ''' card = input() hand = input().split() res = any(map(lambda x: x[0] is card[0] or x[-1] is card[-1], hand)) print('YES' if res else 'NO')
''' @judge CodeForces @id 1327A @name Sum of Odd Integers @contest Educational Codeforces Round 84 @tag Math ''' from sys import stdin def solve(n, k): if k * k > n: return False return n % 2 == k % 2 input() for line in stdin: n, k = map(int, line.split()) print('YES' if solve(n, k) else 'NO')
''' @judge CodeForces @id 394A @name Counting Sticks @tag String Manipulation ''' import re def stickToTuple(s): temp = re.match(r'(\|+)\+(\|+)=(\|+)', s) return tuple(map(len, temp.groups())) def tupleToStick(a, b, c): return '{}+{}={}'.format('|' * a, '|' * b, '|' * c) def solve(a, b, c): ...
def bubble_sort(lst): for i in range(len(lst)-1): for j in range(len(lst)-i-1): if lst[j] > lst[j+1]: lst[j],lst[j+1] = lst[j+1],lst[j] return lst lst = [2,3,5,1,8,7,6] print(bubble_sort(lst))
import re msg = '<h1>11111</h1>' pattern = r'<.+>(.*)</.+>' result = re.match(pattern, msg) print(result.group()) # number msg1 = '<h1>2222</h1>' pattern1 = r'<(.+)>(.*)</\1>' # \1表示引用分组内容 print(re.match(pattern1, msg1)) print(re.match(pattern, msg)) # 起名的方式 (?P<名字>pattern) (?P=名字) msg2 = '<html><h1>333<h1><html>' ...
#Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. # Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. # In other words, check if it is possible to make a square using two gi...
'''Python 3 Code for the align numbers up to n^2 in a spiral challenge. The output layout can be slighthly changed by setting another character as SPACINGSYMB. -nighmared''' NUMBER = int(input('Base: ')) SPACINGSYMB = ' ' #Symbol used to align the output better print('{}\n'.format(NUMBER)) def makepowlist(n):return(li...
""" def factorial(n): f = 1 for i in range(1,n + 1): f *= i return f """ def Z(n): """ 20 = 5 * 2 * 2 25 = 5^2 50 = 5^2 * 2 """ count5 = 0 i = 1 while 1: a = pow(5, i) if a > n: return count5 else: count5 += n/a ...
from functools import reduce # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: num_one = [] num_two = [] _sum...
import sys input = sys.stdin.readline n = int(input()) coords = [list(map(int, input().split())) for _ in range(n)] coords.sort(key=lambda x: (x[0], x[1])) for coord in coords: print(' '.join(list(map(str, coord))))
b = 5 a = 3 a *= b # a * b print('1. ' + str(a)) a = 99 a /= b # a / b print('2. ' + str(a)) a = 99 a //= b # a / b の整数値 print('3. ' + str(a)) a = 8 a %= b # a を b で割った余り print('4. ' + str(a)) a = 3 b = 3 a **= b # a を b 回掛ける print('5. ' + str(a))
# パターン1 def merge(array2): merge_list = [] array1 = list(range(1, len(array2) + 1)) for a1, a2 in zip(array1, array2): merge_list.append((a1, a2)) print(merge_list) # パターン2 def merge2(array): merge_list = [] for i, a in enumerate(array, start=1): merge_list.append((i, a)) pr...
"""16. 1부터 50 까지의 숫자 중에서 3의 배수를 공백으로 구분하여 출력하시오.""" for k in range(1, 51): if k % 3 == 0: print(k, end = ' ')
import random class WisdomRoom(object): def __init__(self): self.rightAns = False self.count = 0 def intro(self): print "Now you enter the wisdom room, you can only pass the room by answer the question correctly." def q1(self): print "what object has four legs in the morning, two legs at noon, three le...
#!/usr/bin/env python3 """ number_guessing_game.py This program makes up a secret (random) number between 1 and 10, and gives the user 3 tries to guess it. If the user hasn't guessed after three tries, then number is revaled. """ import random def main(): randint = random.randrange(10) + 1 # gets a number 1-10 i...
#!/usr/bin/env python3 """ random_walker1.py This program models a "random walker" that starts at location 0,0, an intersection in the middle of a city laid out in square blocks. Each turn, the random walker moves one block to the north, east, west, or south, with the x-coordinate changing by 1 block or the y-coordin...
#!/usr/bin/python import sys import os import time def main(): os.system('clear') mylst=input("please enter the list of words") mynum=input("please enter the filter value") start=time.time() lst=filter_long_words(mylst,mynum) print("filtered list=",lst) print("time taken:",time.time()-start) def filter_long_word...
#!/usr/bin/python import sys import os import time def main(): os.system('clear') given=input("enter the list of numbers\n") start=time.time() tot=sum(given) pro=mul(given) print("sum="+str(tot)) print("product="+str(pro)) print("time taken:",time.time()-start) def sum(data): ans=0 for num in data: ans=ans+...
#!/usr/bin/python import sys import os import time def main(): os.system('clear') a="bottles of beer on the wall," b="bottles of beer." c="Take one down, pass it around," d=" bottles of beer on the wall." i=99 start=time.time() while(i>0): print(str(i)+a+str(i)+b) i=i-1 print(c+str(i)+d) i=i-1 print("t...
#!/usr/bin/python import sys import os import time def main(): os.system('clear') wrdlst=input("please enter the list of words") start=time.time() lenlst=Word_to_Length_map_func(wrdlst) print("the length of the corresponding words are:",lenlst) print"time taken",time.time()-start def Word_to_Length_map_func(mydat...
# 8 kyu # Count Odd Numbers below n # Given a number n, return the number of positive odd numbers below n, EASY! # oddCount(7) //=> 3, i.e [1, 3, 5] # oddCount(15) //=> 7, i.e [1, 3, 5, 7, 9, 11, 13] # Expect large Inputs! def odd_count(n): return n // 2
import unittest from tree.tree import Tree,Node class TestPrintTree(unittest.TestCase): def test_1(self): self.test = Node(3,None,None) self.answer = [[3]] assert Tree(self.test).printTree()== self.answer def test_2(self): self.test = Node(1,Node(2,Node(3,None,None),Nod...
""" # Definition for a Node. class Node(object): def __init__(self, val=0, left=None, right=None, next=None): self.val = val self.left = left self.right = right self.next = next """ class Solution(object): def connect(self, root): queue, result = [], [] if root is...
from hasher import decode_password, encode_password, hash_master_password import elara from stdiomask import getpass def new_password(db): website = input("Enter website for which password must be saved - ") password = getpass(prompt = "Enter password to be saved - ", mask = '*') db.set(websit...
class Nodo(object): def __init__(self, nombre, heuristica=0, profundidad=0): self.nombre = nombre self.nodosAdyacentes = dict() self.heuristica = heuristica self.profundidad = profundidad def addNodoAdyacentes(self, nodo, peso=0): self.nodosAdyacentes[nodo.nombre] = pes...
import random print("What is your name?") name = input().capitalize() secretnumber = random.randint(1,20) print("Well, " + name + ", guess a number between 1 to 20") for guessestaken in range(1,7): guess = input() try: if int(guess) < secretnumber: print("Guess higher.") ...
#!/usr/bin/env def digits_count(val): """ Estimate number of digits for input value. :param val: input value :type val: int :returns: int -- number of digits """ if val == 0: return 0 n_digits = 1 while val // 10 > 0: n_digits += 1 val /= 10 return n_digit...
#!/usr/bin/env import functools import time def timing(func): """ This function calculates time requires to execute function "func". :param func: function to input :type func: function :returns: time required """ @functools.wraps(func) def wrapper(*args, **kwargs): start = t...
#!/usr/bin/env python3.6 # Декоратор - это обертка для функции, которая позволяет # трансформировать внутреннюю функцию, как мы хотим. # Дескриптор делает похожее, переписывая протоколы __get__, # __set__ и __delete__, поэтому сделав атрибут класса экземпляром # декскриптора, мы можем воздейстовать на этот атрибут. c...
x = abs(int(input("input 1st value: "))) # 1st value y = abs(int(input("input 2nd value: "))) # 2nd value while (x!=0) & (y!=0): # until values become 0 if x > y: # looking for bigger value x = x % y # updating it with mod else: y = y % x # updating print (x+y) # greatest common diviser
import datetime class InvalidLocationError(Exception): """ Raised in case of {"error":true,"detail":"Access forbidden, you have no acces for this locale: 1992"} """ pass class InvalidDateError(Exception): """ Raised in case of data isn't in the format YYYY-MM-DD """ pass def validat...
import sys DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'} OTHER_SYMBOLS = {'+', '-', '*', '/', '(', ')'} END_EXPRESSION = '.' class Lexer: def __init__(self, word): self.word = word self.cur = 0 self.last = False def next_token(self): symbol = self.word[self.cur]...
import sys class Node: """Binary tree node""" def __init__(self, key: int): self.left = None self.right = None self.key = key self.height = 1 def balance_tree(root: Node): root.height = 1 + max(get_height(root.left), get_height(root.right)) if get_balance(root) > 1: ...
from random import randint list_lenght = int(input()) raw_list = list(map(int, input().split(' '))) assert(len(raw_list) == list_lenght) def quick_sort_step(input_list, l, r): ind = randint(l+1, r) x = input_list[ind] input_list[ind], input_list[l] = input_list[l], input_list[ind] i = l ll = l ...
import sys class Node: def __init__(self): self.next = [None] * 26 self.is_terminal = False class Trie: def __init__(self): self.root = Node() def insert(self, s, node): ind = ord(s[0]) - 97 if node.next[ind] is not None: next_node = node.next[ind] ...
import random elementos = [1, 1, 5, 1, 3] probabilidades = [0, 0.027, 0.054, 0.729, 0.756, 1] dardo = random.random() print(dardo) elegido = 0 for i in range(len(probabilidades)): if dardo < probabilidades[i+1]: elegido = elementos[i] print(elegido) break
'''brain-progression game logic''' from random import randint WELCOME_STRING = 'What number is missing in the progression?' LENGTH_MIN = 5 LENGTH_MAX = 10 FIRST_ELEMENT_MIN = 5 FIRST_ELEMENT_MAX = 15 DELTA_MIN = 5 DELTA_MAX = 15 def get_progression(first_element, delta, length): progression = [] for step i...
import sys, random, time, os, datetime, square, board, misc, learning class game: """A game object. Contains the 9 boards and other attributes associated with a game. Also contains the functions required to play the game to supplement the helper function in board.py""" def __init...
#!/usr/bin/python3 # Shyam Govardhan # 6 December 2018 # Coursera: The Raspberry Pi Platform and Python Programming for the Raspberry Pi # Module 4 Assignment import time import RPi.GPIO as GPIO ledPin = 7 buttonPin = 8 BLINK_SPEED = .5 def init(): GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.set...
import re def keywordsExtract(): sentence = input("Enter your string: ") words_list = [] keywords_list = [] userless_list = ["in", "on", "the", "hii", "and", "for", "if", "the", "else", "then", "but", "of", "then", "or", "get", "put", "why", "how", "are", "you", "is", "contain", "this", "a", "an", "if...
from tools import estrutura_dados as No def breadth_first_search(mapa, inicio, fim): # Criar listas para nós abertos e nós fechados aberto = [] fechado = [] # Crie um nó representando o inicio e o objetivo inicio_node = No.No(inicio, None) objetivo = No.No(fim, None) # Adiciona nó inicial ...
# -*- coding: utf-8 -*- def foreign_exchange_calculator(ammount): mex_to_col_rate = 145.97 return mex_to_col_rate * ammount def run(): print('CALCULADORA') print('Convierte de pesos meicanos a pesos colombianos.') print('') ammount = float(raw_input('Ingresa la cantidad de pesos mexicanos qu...
#AIM: Write a Python program to plot the function y=x**2 using the pyplot or matplotlib libraries. import matplotlib.pyplot as plt import numpy as np x = np.arange( -10 , 10 ) y = np.square( x ) plt.plot( x , y ) plt.show()
FavoritePokemon = "crobat, squirtle, pikachu, chikorita, lugia, sylveon" reverse = [] index = len(FavoritePokemon) while index > 0 : reverse =+ FavoritePokemon [index -1 ] index= index - 1 print reverse
#Albert ''' this function asks for age, citizen, and residency. If the age is atleast 35, the person is an American citizen, and years of residency is atleast 14, the person is elgible to run for president. If these requirements are not met, there would be text indicating what the person is missing. ''' def president(...
data = [1, 2, 3, 2, 5] m = 5 n = 5 start = 0 end = 0 count = 0 interval_sum = 0 # 고려해야 하는 사항들 # 1. interval_sum > m 일때 # 2. interval_sum < m 일때 # 3. interval_sum == m 일때 while end < n and start < n: if interval_sum > m : print("전 start", start) interval_sum -= data[start] start += 1 ...
numbers = [0, 1, 0, 0, 0] numbers = list(map(str, numbers)) numbers.sort(key = lambda x : x*3, reverse = True) print(numbers) print((''.join(numbers))) # def change(numbers,x,y): # temp = 0 # index_x = numbers.index(x) # index_y = numbers.index(y) # temp = numbers[index_x] # numbers[index_x] = ...
from random import random, randint from skimage import draw import math import numpy as np class ImageAugmenter(): """ Modify input images for data augmentation. Draw ellipse_count ellipses, each with a random color in the part of the image given by 'area'. Area is height x width fraction is from 0.0 t...
__author__ = 'dare7' # for development in external local IDE and to be complied with Codeskulptor at the same time try: import simplegui except ImportError: import SimpleGUICS2Pygame.simpleguics2pygame as simplegui simplegui.Frame._hide_status = True import random, math # template for "Guess the number" ...
from random import choice # Q2 gestures = ["rock", "paper", "scissors"] # Q3 def numb_rounds(): while True: n_rounds = input("Please input an odd number of rounds to play: ") try: if int(n_rounds) % 2 != 0: print("Got it.") break elif ...
birthdays = {'alice':'4/1','bob':'2/1', 'iva':'2/21'} while True: print('please input the name. if you want to quite, please enter ') name = input() if name == '': break if name in birthdays: print(name + 'birthday is' + birthdays[name]) else: print(name + 'birthday is not ...
# Welcome to the Week 7 CodeBench exercise set. As with the Week 6 set, we start with some revision exercises, and then have some slightly longer algorithm design questions to finish. # # The code below defines a Person class. Each person has a name and a list of friends that other pople can be added to. # # You jobs ...
import timeit import copy print("Ingrese el tamaño del arreglo.") basura = input() print('Ingrese los numeros del arreglo.') entrada = input() def transformar_input(entrada): res = [] for num in entrada.split(): res.append(int(num)) return res entrada = transformar_input(entrada) def crear_li...
n = int(input('Enter a number: ')) print(f'''Predecessor: {n - 1} Successor: {n + 1}''')
t = int(input('How many days rented? ')) d = int(input('How many kilometers traveled? ')) print(f'Total: R${(60 * t) + (0.15 * d)}')
n1 = int(input('Enter a value: ')) n2 = int(input('Enter another value: ')) print(f'The sum between {n1} and {n2} is {n1 + n2}')
#! /usr/bin/env python """ regularized_logistic.py Python implementation of part 2 of coding exercise 2 for Andrew Ng's coursera machine learning class (week 3 assignment) """ import numpy as np import matplotlib.pyplot as plt import scipy.optimize as optimize """ Part 1: visualize the data """ # load data dat2 ...
''' "Факторіал" Реалізуйте функцію factorial(n) яка повертає факторіал натурального числа. ''' def factorial(n): # ваш код assert factorial(1) == 1 assert factorial(2) == 2 assert factorial(3) == 2 * 3 assert factorial(4) == 2 * 3 * 4 assert factorial(5) == 2 * 3 * 4 * 5 assert factorial(6) == 2 * 3 * 4 * 5 * 6 ass...
# Double Every Other # https://www.codewars.com/kata/5809c661f15835266900010a def double_every_other(lst): for i in range(1, len(lst), 2): lst[i] *= 2 return lst assert double_every_other([1,2,3,4,5]) == [1,4,3,8,5] assert double_every_other([1,19,6,2,12,-3]) == [1,38,6,4,12,-6] assert double_every_other([-1000,...
# Count of positives / sum of negatives # https://www.codewars.com/kata/576bb71bbbcf0951d5000044 def count_positives_sum_negatives(arr): if len(arr) == 0: return [] positives_count = 0 sum_negatives = 0 for i in arr: if i > 0: positives_count += 1 if i < 0: sum_negatives += i return [positives_count, ...
''' "Матриця" Реалізуйте функцію print_matrix(). Функція отримує матрицю чисел — список, елементами якого є списки (рядки), елементами яких у свою чергу є цілі числа (колонки). Функція виводить матрицю у вигляді таблиці. Якщо функції передано матрицю [[1,2,3],[4,5,6],[7,8,9]] то вивід має бути наступним: 1 2 3 4 5 6 7...
''' "" , . -: 23, 35, 100, 12121. : 123, 9980. next_doubleton(num). num. - num. ''' # # https://www.codewars.com/kata/604287495a72ae00131685c7 def is_doubleton(num): digits = [0] * 10 for ch in str(num): digits[int(ch)] = 1 return sum(digits) == 2 def next_doubleton(num): while Tru...
''' "Сума цифр" Реалізуйте функцію sum_of_digits(). Функція отримує число, повертає суму цифр цього числа. ''' def sum_of_digits(number): # ваш код num_as_str = str(number) sum = 0 index = 0 while index < len(num_as_str): if num_as_str[index] in '0123456789': sum += int(num_as_str[index]) index += 1 retu...
''' Напишіть програму яка виконує наступне: 1. Змінній a присвоїти значення 4 2. Змінній b присвоїти значення 3 3. Обчислити суму квадратів a та b. Результат присвоїти змінній result 4. Вивести в термінал значення змінної result ''' # ваш код починається з наступного рядка a = 4 b = 3 result = a*a + b*b print(result) ...
# Data cleaning means fixing bad data in your data set. # Bad data could be: # 1. Empty cells # 2. Data in wrong format # 3. Wrong data # 4. Duplicates import pandas as pd our_dataset = pd.read_csv("dirtydata.csv") print(our_dataset) # The data set contains some empty cells ("Date" in row 22, and "Calories" in row ...
# Cells with data of wrong format can make it difficult, or even impossible, to analyze data. # To fix it, you have two options: remove the rows, or convert all cells in the columns into the same format. # Convert Into a Correct Format # In our Data Frame, we have two cells with the wrong format. # Check out row 22 an...
''' Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue. Note: The number o...
class Student(object): def __init__(self, name, gpa, age): self.name = name self.gpa = gpa self.age = age def __str__(self): return "Name: %s GPA: %f Age: %d" % (self.name, self.gpa, self.age) def __lt__(self, other): """ comparison based on: https://pi...
from student import Student from random import shuffle import unittest def custom_cmp(x, y): if cmp(x.gpa, y.gpa): return cmp(x.gpa, y.gpa) elif cmp(x.name, y.name): return cmp(x.name, y.name) else: return cmp(x.age, y.age) class StudentTests(unittest.TestCase): def test__st...
print('Ingresa un numero, y te dare todos los naturales hasta él') entrada = int(input()) for i in range(entrada+1): print(i)
#!/usr/bin/env python # coding: utf-8 # In[1]: lst1=[] def lst_sqre(lst): for i in lst: lst1.append(i*i) return lst1 # In[2]: lst_sqre([1,3,5,7,8]) # In[4]: lst=[1,2,3,4,5,6,7,8] # In[5]: lst1=[i*i for i in lst] print(lst1) # In[8]: lst1=[i*i for i in lst if i%2!=0] print(lst1) # I...
#!/usr/bin/env python # coding: utf-8 # In[6]: class Teach: def __init__(self,n,w): self.name=n self.work=w def do_work(self): if self.work=="teacher": print(self.name,"teaching java") elif self.work=="labasst": print(self.name," teaching you p...
"""asd""" # from random import choice, randrange from math import sin, cos from drawable_item import DrawableItem from random import randrange class Enemy(DrawableItem): """Enemy is something that moves...""" def __init__(self, hero, background): self.hero = hero super(Enemy, self).__init__(...
class PriorityQueue: """Implementation of priority queue""" def __init__(self): self.array = [] self.heap_size = 0 def _sift_up(self, index): parent_node = index//2 if index == 1 or self.array[index-1] <= self.array[parent_node-1]: return self.array[ind...
import unittest from binary_search import binary_search class TestBinarySearch(unittest.TestCase): def test_1(self): array = [1, 5, 8, 12, 13] numbers = [8, 1, 23, 1, 11] result = [] for n in numbers: result.append(binary_search(array, n)) self.assertEqual(resul...
# 求100以内所有的奇数之和 # 获取所有100以内数 # i = 0 # # 创建一个变量,用来保存结果 # result = 0 # while i < 100 : # i += 1 # # 判断i是否是奇数 # if i % 2 != 0: # result += i # print('result =',result) # 获取100以内所有的奇数 # i = 1 # while i < 100: # print(i) # i += 2 # 求100以内所有7的倍数之和,以及个数 i = 7 # 创建一个变量,来保存结...
# 水仙花数是指一个 n 位数(n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身(例如:1**3 + 5**3 + 3**3 = 153)。 # 求1000以内所有的水仙花数 # 获取1000以内的三位数 i = 100 while i < 1000: # 假设,i的百位数是a,十位数b,个位数c # 求i的百位数 a = i // 100 # 求i的十位数 # b = i // 10 % 10 b = (i - a * 100) // 10 # 求i的个位数字 c = i % 10 # print(i , a , b ...
def sub_num(a,b): return a-b print(sub_num(1,3)) # -2 def mul_num(a,b): return a*b print(mul_num(1,3)) # 3
#1. 1,2,3,4 요소를 가진 배열을 생성하고 다음을 구현하라. list1 = [1,2,3,4] ##생성한 배열에 5,6,7,8을 추가하라. list1 = list1 + [5,6,7,8] print(list1) ##생성한 배열의 인덱스가 4인 값을 찾아라. print(list1[4]) ##생성한 배열의 인덱스가 3~6인 값을 찾아라. print(list1[3:6]) #2. “I love you, John!”이라는 문자열을 생성하고 다음을 구현하라. ##위 문자열을 공백을 기준으로 나누어 배열 a에 저장하라. ##John이 들어있는 배열은 a의 몇 번째 배열에...
"""sierpinski_triangle.py Author: Harman Suri Nov 15, 2020 Description: Draws the Sierpinski Triangle fractal by using the turtle module and recursion. """ import turtle # creates new turtle drawer = turtle.Turtle() # height and width of screen h = 600 w = 600 # creates new scre...
from cs50 import SQL from sys import argv if len(argv) != 2: # Checks for the correct amount of argv print("Usage: python roster.py house") exit() db = SQL("sqlite:///students.db") # Reads all the info the program is going to print from the table roster = db.execute("SELECT first, middle, last, birth FROM s...
""" classes.py This is a rough prototype of the discrete data entities in this project. It's intended more to be a reference than a functioning prototype, but it should run and you should be able to perform basic tests with it for your own understanding. I'm making it for mine too, to start. It's to make the way ah...
from calendar_automation import get_calendar_service def calendar_list(): service = get_calendar_service() print('\nHere are the names of your calendars:\n') calendars_result = service.calendarList().list().execute() calendars = calendars_result.get('items') if not calendars: prin...
def main(): count = 0 mylist = [] while count < 10: element = input("Enter the element of list: ") try: element = int(element) except: print("Invalid input. Enter again.") else: count +=1 mylist.append(element) count = len(mylist)-1 flag = True while flag == True: #It will end th...
def leng(a): required = len(a) return required def two(): string = input("Enter a string: ") print(leng(string)) two()
def main(): count = 0 mylist = [] while count < 10: element = input("Enter the element of list: ") try: element = int(element) except: print("Invalid input. Enter again.") else: count +=1 mylist.append(element) for i in range(len(mylist)-1): #this loop is used for the number of tim...
def main(): #taking two variables as 0 and 1 to start the series var01 = 0 var02 = 1 fibonacci = [var01,var02] #The starting values of the series are included in the list for var in range(1,10): var03 = var01 + var02 var01 = var02 var02 = var03 fibonacci.append(var03) #appending each new value ...
def main(): listing = [] num = input("enter a number between 10-100: ") try: num = int(num) except: print("invalid input.") num = 0 while (num>= 10) and (num <= 100): if not(num in listing): listing.append(num) num = input("enter a number between...
def reverse(a): required1 = a.find(" ") if required1: reversing1 = a[required1::-1] required2 = a.find(" ",required1+1) if required2: reversing2 = a[required2:required1:-1] required3 = a.find(" ",required2+1) if required3: reversing3 = a[required3:required2:-1] ...
""" 判断输入的边长能否构成三角形,如果能则计算出三角形的周长和面积 Version: 0.1 Author: Robert Xu """ first_edge = float(input('请输入第一条边的长度:')) second_edge = float(input('请输入第二条边的长度:')) third_edge = float(input('请输入第三条边的长度:')) if first_edge + second_edge > third_edge and first_edge + third_edge > second_edge and second_edge + third_edge > first_ed...
def without_string(base, remove): output = [] normalised_remove = remove.lower() remove_length = len(normalised_remove) normalised_base = base.lower() base_length = len(base) i = 0 while i < base_length: candidate = normalised_base[i:i + remove_length] if candidate == norm...