text
stringlengths
37
1.41M
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example 1: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: "cbbd" Output: "bb" O(n*n)。对于每一个字符,以之作为中间元素往左右寻找。 注意 1.处理奇偶两种模式:aba, abba 2.奇偶两种情况都得算,然后做比较才能得出longest。因为...
class Counter(dict): def __missing__(self, key): return 0 def anagram(str1='', str2=''): str1 = str1.replace(' ','').lower() str2 = str2.replace(' ','').lower() if len(str1) != len(str2): return False counter = Counter() for el in str1: counter[el] += 1 for el in s...
l = list(range(1, 100)) for a in l: count = 0 for i in range(2, (a // 2 +1)): if (a % i == 0): count = count + 1 break if(count ==0 and a != 1): print("Prime Number is: ", a)
#! /usr/bin/env python3 print("Hello, World") name = input("Who are you? ") print("Indeed, {}.".format(name))
def recursion(num): if num==1: return num else: return num*recursion(num-1) Number=int(input("Enter the number to find Recurdion:")) #result=recursion(Number) result=recursion(Number) print("recursion factorial is ", result)
num1=int(input('Digite o primeiro número: ')); num2=int(input('Digite o segundo número: ')); print('Antes %d' %num1, 'e %d' %num2); num1, num2 = num2, num1; print('Depois %d' %num1, 'e %d' %num2);
nume=int(input('Digite um valor inteiro maior que 0: ')) if nume>0: den=1 num=1 while num<=nume: print(' %d/%d '%(num,den), end='') num+=1 den+=2 else: print('Valor Inválido')
custo = int (input ('Digite o custo de fábrica do carro: ')); distri = custo * 32 / 100; impos = custo * 41 / 100; result = custo + distri + impos; print ('O custo é igual a %d' %result);
num1=int(input('Digite o número: ')); result=num1+1; result2=result+1; result3=result2+1; print('Os números são %d' %result, ', %d' %result2, 'e %d' %result3)
'''Sistema para acréscimo de nota Conforme combinado com os estudantes: -Aluno com nota azul no trabalho recebe um ponto na média -Aluno com nota vermelha no trabalho perde 0,5 ponto na prova mensal -Com a média azul sendo par o aluno recebe uma caneta azul de prêmio, caso seja ímpar recebe uma caneta preta.''' print(...
cont = 1 neg = 0 while cont <= 5: num=int(input('Escreva um valor: ')) if num<0: print('O número %d' %num, ' é negativo') neg = neg + 1 cont=cont+1 print('A quantidade de nº negativos é %d' %neg) print('Fim do programa')
num=[0]*5 i=0 while (i<5): num[i]=int(input('Digite um valor: ')) i=i+1 impar=num[i]%2 i=0 if impar!=0: result=impar print(result)
import pandas as pd import numpy as np import matplotlib.pyplot as plt import mglearn from pandas.plotting import scatter_matrix from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split # this initiate the class KNeighborsClassifier so we can use the prediction model from sklearn.neig...
'''Extract a structured data set from a social media of your choice. For example, you might have user_ID associated with forum_ID. Use relational algebra to extract a social network (or forum network) from your structured data. Create a visualization of your extracted network. What observations do you have in regards t...
# all the class logic class Car: """ Class car props - registrationNumber(str), color(str), slotNumber(int) methods - getter for registrationNumber and color. getter and setter for slotNumber. """ def __init__(self,registrationNumber,color): """ constr...
#!/usr/bin/python nume=input ("ingrese dia de la semana: ") dias = {1: "Domingo", 2: "Lunes", 3: "Martes", 4: "Miercoles", 5: "Jueves", 6: "Viernes", 7:"Sabado"} if (nume) <= 7: dia= dias [nume] print "El dia es: %s" % (dia) else: print "El numero %s no es valido" % (nume)
#everytime a computation is correctly executed, a .txt file is created #everytime this script runs, it overrides the previous .txt files import json from calculator import Calculator1 if __name__ == "__main__": calc = Calculator1("calculator_1"); # op = Operation("operation_1") n = 1 # JSON_outputn.txt...
# Ліпше стилізувати словники наступним чином # це дозволить ліпше сприймати інформацію names = { 'Taras':'Taras Palagnuk', 'Nazar':'Nazar Gardienko', 'Andrey':'Andrey Myzik', 'Vlad':'Vlad Kulcziskiy', 'Franc':'Franc Gaur' } # бажано старатися мінімізувати логічні вкладення і розбивати їх на блоки #...
import pickle def main(): ## Display the data for an individual country. nations = getDictionary("UNdict.dat") nation = inputNameOfNation(nations) displayData(nations, nation) def getDictionary(fileName): infile = open(fileName, 'rb') nations = pickle.load(infile) infile.clo...
def main(): winnerslist=getlistfromfile("Rosebowl.txt") wins=creatfreqdict(winnerslist) displaywinners(wins) def getlistfromfile(filename): infile=open(filename) winnerslist=[line.rstrip() for line in infile] return winnerslist def creatfreqdict(winnerslist): wins={} for winn...
import requests from bs4 import BeautifulSoup import csv #Here in URL we can use any link of website for copy of that website table data. url = "https://www.website.com" agent = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'} page = requests.get(url, headers=agent) html...
#interactive python program for converting every letter after a fullstop and every starting letter into uppercase letter #the statement is entered by the user sentence = input("Enter the statement:") sen_list=list(sentence) sen_list_final=[] for i in range(len(sen_list)): #checking and conversion to upper case letter ...
#!/usr/bin/env python # Steven Phillips / elimisteve # 2015.07.16 import collections import math import random import exphil def borda(prefs): ''' prefs should be a tuple of tuples indicating preferences. E.g., (('A', 'B', 'C'), ('A', 'C', 'B'), ('C', 'B', 'A')) TODO(elimisteve): Handle ties, like ...
# Created by @Saksham Solanki # This is a program which will control a sophisticated system of lawn mower. # It can detect and avoid obstacles through a method never made before. # It has a simple GUI which is easy to use. The program has 2 modes, out of # which one is Manual Mode --> In this mode the user has to cr...
alien_0 = {'color' : 'green', 'points':5} alien_0['position'] = (0,10); alien_0['speed'] = 'fast' alien_0['speed_1'] = 'medium' del alien_0['speed_1'] print(alien_0 ,"\n") for key,value in alien_0.items(): print("key is " + key.title() +", value is " , value , "\n") for key in sorted(alien_0.keys()): print('key:' ...
# users input is assigned to the number variable Number = int(input('Please enter a postive number: ')) # we need an ititial guess of the square root of number to apply newton's method. # the initial guess should not be zero, or zero will be in the denominator in the function. guess = 1 # how many times we want ...
""" Forward modeling magnetic data using spheres in Cartesian coordinates ----------------------------------------------------------------------- The :mod:`fatiando.gravmag` has many functions for forward modeling gravity and magnetic data. Here we'll show how to build a model out of spheres and calculate the total fi...
class Account: """ A simple account class """ """ The constructor that initializes the objects fields """ def __init__(self, owner, amount=0.00): self.owner = owner self.amount = amount self.transactions = [] def __repr__(self): return f'Account {self.owner},{self.amoun...
""" Dunder methods is a fancy name for 'under under method under under' or __method__() They are built-in functions that add functionality to python code and also unlock new features on objects """ class Garage: """ Stores cars in a garage object """ def __init__(self): self.cars = [] def __len_...
""" Storing and retrieving data using CSV (Comma Separated Values) files """ # READING FROM THE FILE # Ignore the first line --> strip spaces from the second line for lines in lines[1:] using a list comprehension # Open ,read and close the file...iterate over the file contents using a for loop and use item indexes to a...
space="========================================" #1. print("1.") x=int(input("Enter a number: ")) if x%2==0: print("Great!") else: print("Invalid.") print(space) ################################################ #2. print("2.") a=int(input("Number #1: ")) b=int(input("Number #2: ")) c=int(input("Number #3: ")) i...
a=int(input("Enter 1st number: ")) b=int(input("Enter 2nd number: ")) while a+b==10: print(a+b) a=int(input("Enter 1st number: ")) b=int(input("Enter 2nd number: "))
i=0 sum = 0 for i in range(6): x = int(input("Enter number: ")) sum+=x print(sum) print(sum/6)
class Person(): def info(self): print("Name:",self.name) print("Age:",self.age) print("No. of children:",self.children) def hasChildren(self): if self.children==0: return False else: return True def ageGroup(self): if 0<=self.age<18: ...
#If a number is divisible by the sum of its digits, then it will be known as a Harshad Number. For example: # The number 156 is divisible by the sum (12) of its digits (1, 5, 6 ). # Some Harshad numbers are 8, 54 156 num=int(input("enter the harshad number")) i=num sum=0 while i>0: b=i%10 i=i//10 sum=sum+...
#write a program check prime number num=int(input("enter the number")) i=2 while i<num: if num%i==0: print("it is not prime number") i=i+1 else: print("it is prime number")
#write a program using count function in loop i=1 while i<=100: count=0 j=2 while j<=i//2: if i%j==0: count=count+1 break j=j+1 if count==0 and i!=1: print(i) i=i+1
# 1 # 22 # 333 # 4444 # 55555 i=1 while i<=5: j=5 while j>=i: print( " ",end=" ") j=j-1 k=0 while k<=j: print(i,end=" ") k=k+1 i=i+1 print()
class Solution: # @param {integer} n # @return {integer} 'Recursive Binary search: using varying array size' def BinarySearch(self, nums,target): if len(nums)==0: return False mid=int(len(nums)/2) if target<nums[mid]: return self.BinarySearc...
"Ternary search Tree: https://www.youtube.com/watch?v=CIGyewO7868" class Node: def __init__(self,data=None): self.data=data self.right=None self.eq=None self.left=None self.isEndOfString=0 class Ternary: def insert(self,root,word): if not root: ...
#recursion and memoization are used to solve DP problems but they are totally separate things. #And divide and conquer problems differ from DP in that the sub-problems do not overlap. #Divide-&-conquer works best when all subproblems are independent. So, pick partition that makes algorithm most efficient & simply combi...
numero = int(input()) if(i > 1): for i in range(2, numero): if(numero % i == 0): print("No es primo.") break else: print("Es primo.") else: print("No es primo")
## numbers=[] for i in range(10): numbers.append(i) print(numbers) ## numbers=[x for x in range(10)] print(numbers) ## for x in range(10): print(x**2) numbers=[x**2 for x in range(10)] print(numbers) ## numbers=[x*x for x in range(10) if x&3==0] print(numbers) ## myString="hello" myList=[] for letter in mySt...
#Çift sayıların toplamını yazdıran kod. #Continue komutuna gelince program orayı atlar ve başa döner. toplam=0 i=0 while i<100: i+=1 if i%2==1: #Tek sayılar gelince atlıyor. continue toplam+=i print(toplam) #MemduhFırat isminde u harfine gelince atladı fakat çalışmaya devam etti. ...
#Girilecek kelimeyi girilecek sayı kadar ekrana bastıran kod. def EkranaYazdir(kelime, adet): print(kelime*adet) EkranaYazdir('Merhaba\n', 10) #Kendisine girilen sınırsız sayıdaki bilgiyi listeye ekleyen kod. def liste(*args): liste=[] for i in args: liste.append(i) return liste result=liste(10...
#miktar=input("Çekmek istediğiniz tutarı giriniz: ") FiratHesap={ "Ad": "Memduh Fırat Şahin", "HesapNo": "12354648", "Bakiye": 3000, "EkHesap": 2000 } ZahirHesap={ "Ad":"Zahir Şahin", "HesapNo":"1236465", "Bakiye":2000, "EkHesap":1000 } def ParaCek(hesap, miktar): print(f"Merhaba ...
list1= ["Fırat",20,True,5.8] print(list1) print(list1[0]) my_numberlist=["one","two","three"] my_numberlist2=["four","five","six"] numberlist= my_numberlist+my_numberlist2 print(numberlist) numberlist2= [my_numberlist,my_numberlist2] print(numberlist2[0]) lenght=len(numberlist) lenght2=len(numberlist2) print(lenght)...
#Girilen 2 sayıdan hangisi büyüktür? """ a=int(input("a değerini giriniz ")) b=int(input("b değerini giriniz ")) result= (a<b) print(f"a değeri: {a} b değerinden: {b} küçük müdür? {result}") #Kullanıcıdan 2 adet vize (%60) ve 1 final (%40) notu al. Ortalama 50ye eşit veya büyükse geçti, #değilse kaldı yazsın. vize1...
num = input ('give me the number: ') num = int (num) if num < 0 or num > 36 print ('give me a valid number') return if num == 0 color = 'green' elif num >= 1 and num <= 10 \ or \ num >= 19 and num <= 28 if num % 2 == 0 color = 'black' else color = 'red' elif num >= 11 and num <= 18 \...
def check_bin_palindrome(num): c = [] bin_str = str(bin(num))[2:] for i in bin_str: c.append(int(i)) return (c == c[::-1]) def check_num_palindrome(num): c = [] for i in str(num): c.append(int(i)) return (c == c[::-1]) MAX_NUM = 1000000 num = 1 max_sum = 0 w...
NUM = 100 def sum_of_squares( max_num): sum = 0 for i in range(1,max_num + 1): sum += i * i return sum def square_of_sum( max_num): sum = 0 for i in range(1,max_num + 1): sum += i return sum * sum print square_of_sum(NUM) - sum_of_squares(NUM)
''' Тестируем функцию CB_Quotes, определенную в модуле CBR_Daily_Quotes.py Эта функция возвращает "словарь словарей" histquotes = {'0':{}, '15':{}, '30':{}, '90':{}} ''' from CBR_Daily_Quotes import * histquotes = CB_Quotes() # print('Котировки сегодня') # print(histquotes['0']) # print('---') # # print('Котировки 1...
#!/usr/bin/env python # -*- coding: utf-8 -*- from matrix import * #тестирование программы if __name__ == "__main__": try: rle = SLE(5) print("Система уравнений:") rle.print() print('\nРешение системы: ' + str(rle.solve())) print('\nОбратная матрица:') ...
import numpy as np import matplotlib.pyplot as plt from data import data_matrix, mask_matrix, eval_loss def shrinkage_threshold(x, gamma): """ Applies the shrinkage/soft-threshold operator given a vector and a threshold. It's defined in the equation 1.5 in the paper of FISTA. Input: x...
''' ''' def maxItems(numGroups, arr): arr.sort() arr[0] = 1 for i in range(1, numGroups): if arr[i] - arr[i-1] > 1: arr[i] = arr[i-1] + 1 return arr[-1] ''' Top K frequent words https://leetcode.com/discuss/interview-question/542597/ ''' import heapq class Solution: def to...
''' Basic stack: Use list to implement stack ''' ''' The below sum is building min max stack ''' # Feel free to add new properties and methods to the class. class MinMaxStack: def __init__(self): self.minMaxStack = [] self.stack = [] def peek(self): return self.stack[len(self.stack) - 1] def p...
class Solution: def isKangarooWord(self, words, synonyms, antonyms)): if not synonyms and not antonyms: return 0 score = 0 seen= set() seen = collections.defaultdict() for synonym in synonyms: word, syns = synonym.split(":") if word not in...
''' Design Parking Lot System https://leetcode.com/problems/design-parking-system/ ''' ''' 1. Domain Entities: 1. Car : CarSize - CarSize size # or this can be enum 2 CarSize - small = 1 - medium = 2 - large = 3 2. ParkingLot - int capacity_smal...
# -*- coding: utf-8 -*- # Invesigate the demand data for products # First positive sample is extracted # Assuming the 0 demand at the beginning of each series are due to the new product # New products do not have demand before they are commercialized import numpy as np import pandas as pd import util file...
from tensorflow.examples.tutorials.mnist import input_data import keras as ks from keras.layers import Conv2D, MaxPooling2D, Dense, Dropout, Flatten, Activation import tensorflow as tf import numpy as np mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) train_images = mnist.train.images train_labels = mn...
x = input("Enter a word here: ") def foo(s): ret = "" i = True for char in s: if i: ret += char.lower() else: ret += char.upper() if char != ' ': i = not i return ret def replace_vowel(s): word = foo(x) vowels = ("A", "E", "I", "O", "U...
"""This code solves the lorentz system""" import numpy as np class Lorentz: """This is the Lorentz Class""" def __init__(self,x,y,z,sigma,beta,rho): self.x=np.array([x]) self.y=np.array([y]) self.z=np.array([z]) self.sigma=sigma self.beta=beta self.rho=rho de...
""" Traveling Salesman problem for 2d (x,y) case author: Valentyn Stadnytskyi data: 2017 - Nov 17 2018 The traveling salesman algorithm takes an input array of coordinates and vary array (True/False) """ __vesrion__ = '1.0.0' from time import time, sleep import sys if sys.version_info[0] == 2: from time import c...
class Patient (object): id=0 def __init__ (self,name,allergies): patient.id +=1 self.name = name self.allergies = allergies self.bed_number = None return self class Hospital (object): bed_number = 0 def __init__ (self,hospital_name,capacity): self.pat...
import sys def sum_values(a,b,c): ''' adding parametes Parameters a (int) b (int) c (int) Returns sum (int): sum of above number based on condition ''' temp=[13,14,17,18,19] sum=a+b+c sum= sum-a if a in temp else sum sum= sum-b if b in temp else sum ...
# WriteTweets Class # Programmed by: Jesse Smith # Course: CIS225E-HYB1 # Description: Write lists of tweets by ReadTweets class to files. # This removes usernames and creates anonymity of tweets from read import ReadTweets class WriteTweets(ReadTweets): def __init__(self, filename): ReadTweets.__...
i=int(input()) j=int(input()) k=int(input()) if(i>=j and i>=k): print(i) elif(j>=i and j>=k): print(j) else: print(k)
def leapyear(year: int): if(year % 4 == 0): #divisible by 4 if(year % 100 != 0): #but not divisible by 100 return True elif(year % 400 == 0): #unless divisible by 400 return True return False
# -*- coding: utf-8 -*- """ Created on Mon May 6 12:46:20 2019 @author: mynam """ grid = list() for i in range(6): row = input().strip().split(' ') row = list(map(int, row)) grid.append(row) # start max_hourglass_sum at smallest possible hourglass hourglass_values = [] for i in range(...
#coding: utf-8 import math def d(x1,y1,x2,y2): d = math.sqrt(((x1-x2)**2) + ((y1-y2)**2)) return d if __name__ == "__main__": print("Entre com X1") x1 = eval(input()) print("Entre com Y1") y1 = eval(input()) print("Entre com X2") x2 = eval(input()) print("Entre com Y2") y2 = eval(input()) if d(x1,x2,y1,y2)...
# ************************************************ # Point.py # Define a classe Ponto # Autor: Márcio Sarroglia Pinho # pinho@pucrs.br # ************************************************ class Point: def __init__(self, x=0,y=0,z=0): self.x = x self.y = y self.z = z #p...
import math def _money(): money=int(input("You have an amount of: ")) return money def aplprc(): apl_price=int(input("An apple costs: ")) return apl_price def maxapls(): max_apls=int(money/apl_price) return max_apls def getTotal(): total=apl_price * max_apls return total def getChan...
from random import random from random import randint import sys def main(): w = randint(int(sys.argv[1]), 2 * int(sys.argv[1])) print w a = randint(int(sys.argv[2]), int(sys.argv[2])) syllabus = [] for i in range(w): syllabus.append([]) for i in range(a): name = 'HW' + str(i) ...
n = int(input()) min_name = '' min_time = 10000000 for _ in range(n): time, name = input().split(' ', 1) if int(time) < min_time: min_time = int(time) min_name = name print(min_name)
#!/usr/env/python # _*_ coding: utf-8 _*_ """ 排序算法 reference-link: [1]-https://sites.fas.harvard.edu/~cscie119/lectures/sorting.pdf [2]-https://en.wikipedia.org/wiki/Shellsort [3]-https://en.wikipedia.org/wiki/Quicksort [4]-https://www.geeksforgeeks.org/hoares-vs-lomuto-partition-scheme-quicksort/ [5]-http://personal....
#!/usr/bin/python # -*- coding: UTF-8 -*- import GraphVisual from binaryTree import BinaryTree from binaryTree import TreeNode class BinarySearchTree(BinaryTree): """ 二叉搜索树 """ def __init__(self): self.root = None def __init__(self, data_array): if type(data_array) is not li...
#!/usr/bin/python # -*- coding: UTF-8 -*- from binaryTree import BinaryTree from GraphVisual import GraphVisualization class BinaryHeap(object): """ 二叉堆 基于数组实现 堆元素索引从0开始 """ @staticmethod def compare_less(x, y): return x < y @staticmethod def compare_greater(x, y): ...
#!/usr/env/python # _*_ coding: utf-8 _*_ """ 阶乘调用堆栈: factorial(5) factorial(4) factorial(3) factorial(2) factorial(1) return 1 return 2*1 = 2 return 3*2 = 6 return 4*6 = 24 return 5*24 = 120 """ class Solution(object): @staticmethod ...
# -*- coding: utf-8 -*- """ Tarea 4, Problema 06 Brenda Paola García Rivas No cuenta: 316328021 Taller de Herramientas Computacionales """ #Calcular el promedio de 10 datos #No sé bien cómo hacerlo sin listas:( n1=int(input('Primer dato:')) n2=int(input('Segundo dato:')) n3=int(input('Tercer dato:')) n4=int(input('Cua...
# -*- coding: utf-8 -*- """ Tarea 4, Problema 05 Brenda Paola García Rivas No cuenta: 316328021 Taller de Herramientas Computacionales """ #Culcular la suma de los primeros n enteros def sumar(n): return (n * (n+1)) / 2 #Fórmula n = int(input('Ingrese un número natural: ')) suma= sumar(n) print ('Resultado: ', suma...
# Comparision operators # <,>,>=,<=,==,!= # Can be used in chain comparision operations # Membership operator ### The IN statement checks if a variable is also found in another variable. # Boolean operators ### True. Numerical substitute is 1 ### False. Numerical substitute is 0 print(True) print(False) print(T...
import csv def get_file_contents(filename): "Get the file contents of a CSV. Return the entries and a list of fieldnames." with open(filename) as f: reader = csv.DictReader(f) entries = list(reader) fieldnames = reader.fieldnames return entries, fieldnames def anonymize(entri...
# Language translator # Rules: all vowels will be equal to (g) def translate(phrase): vowels = "aeiou" new_lang = "" for char in phrase: if char.lower() in vowels: if char.isupper(): char = "G" new_lang += char else: char = "g"...
import time import pandas as pd import numpy as np import calendar from datetime import datetime CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and...
hora_entrada = int(input('Digite aqui a hora de entrada: ')) minutos_entrada = int(input('Digite aqui os minutos de entrada: ')) hora_saida = int(input('Digite aqui a hora de saida: ')) minutos_saida = int(input('Digite aqui os minutos de saida: ')) minutos_total_entrada = (hora_entrada * 60) + minutos_entrada minutos...
# 4. SELECTING THE ROOM FOR THE MOVIE # 4.1 Showing the rooms # 4.2 Choosing a room # 4.3 Checking if that room has available sits # 4.4 If the room isn't available, choosing diff room # 4.3 Checking if that room has available sits # 4.4 If the room isn't available, choosing diff room def check(dic,room): if...
# A Dictionary is a collection which is unordered, changeable and indexed. No duplicate members. # simple dict person = { 'frist_name': 'John', 'last_name': 'Doe', 'age': 30 } # Using constructor person = dict(first_name='John', last_name='Doe', age=30) # Access vaue print(person['first_name']) print(pe...
import random guessed = False number = random.randint(1,20) print("I am thinking of a number between 1 and 20. Take a guess") while not guessed: guess = input() guess = int(guess) if guess > number: print("Guess is too high") if guess < number: print("Guess is too low") if guess =...
import os def get_file_path(file_path): filenames = [] sorted_path = os.listdir(file_path) sorted_path.sort() for filename in sorted_path: filename = os.path.join(file_path, filename) filenames.append(filename) return filenames def get_file_path_with_type(file_path, file_type):...
import csv def write_to_csv_file(headers, dict_rows, delimiter=';'): with open('text.csv', 'w', encoding='utf-8') as f: writer = csv.DictWriter(f, headers, delimiter=delimiter) writer.writeheader() for key, value in dict_rows.items(): writer.writerow({headers[0]: key, headers[1...
def ask_user(): expected_answer = "Хорошо" actual_answer = '' while actual_answer != expected_answer: actual_answer = input("Как дела\n") return actual_answer def get_answer(): expected_answer = "Пока" actual_answer = '' while actual_answer != expected_answer: actual_...
from abc import ABCMeta, abstractmethod class IgnitionKey: def start_drive(self): pass class IgnitionButton: def start_drive(self): pass class Car(metaclass=ABCMeta): @abstractmethod def create_starter(self): raise NotImplementedError def drive(self): starter ...
import numpy as np from timeit import Timer #We create an array li = list(range(500)) #The same but with np nump_arr = np.array(li) #Function to do the sum def python_for(): return [num + 1 for num in li] #Function to do the sum def numpy(): return nump_arr + 1 #Results print(min(Timer(python_for).repeat(10, 10...
#Function to verify if the string is palindrome def palindrome(phrase): phrase=phrase.lower() phrase=phrase.replace(' ', '') #If it is a pa or ca, return True return phrase==phrase[::-1] s = input("Ingrese string: ") #We show our string print(s) #We pass the string print(palindrome(s)) #We are reading the file...
# shopping_list = ["milk", "eggs", "bacon"] # # for item in shopping_list: # print("My List:") # print(item) # # print("End of list") # # for x in range(1, 11): # print(x) counter = 0 while(counter < 10): print(counter) counter += 1
# def set_alarm(day): # day = day.lower() # if(day == "saturday" or day == "sunday"): # return None # else: # return "07:00" # # # def add(num1, num2): # return num1 + num2 # # answer = add(2,5) # print(answer) def say_hello(): name = 'Ali' print("Hi " + name) say_hello() prin...
# Vertices are a point in space # There are 8 edges in a cube, so we first # specify all 8 coordinates as vertices DEFAULT_VERTICES = ( (1, -1, -1), (1, 1, -1), (-1, 1, -1), (-1, -1, -1), (1, -1, 1), (1, 1, 1), (-1, -1, 1), (-1, 1, 1) ) # Edges are a line between 2 points/vertices. # Th...
lnum = [23, 35, 35, 654, 46, 345] lnew = [] def randomize(randomlist): random = lnum[0] for x in lnum: if (x % 2 == 0): random = x return random while len(lnum) != 0: x = randomize(lnum) lnum.remove(x) lnew.append(x) print (lnew)
input_name= input('Enter a name') output_text= 'hello'+ input_name print(output_text)
def question_principal(): while True: user_answer = input( "\nWhat is the total value of the house you want to purchase. This is known as your principal. i.e. 500000 ") if user_answer.isdigit(): return int(user_answer) else: print("\nInvalid input. Please ...