text
stringlengths
37
1.41M
import random board = [] show_nums = [] items = ['cat', 'bowl', 'stick', 'flower', 'cup', 'baseball'] items *= 2 while items: board.append(items.pop(random.randint(0, len(items)-1))) # Print board nicely for i in range(len(board)): if (i + 1) % 3 == 0: end = '\n' else: end = ' |' pri...
from time import sleep # #Print literals # print (9) # print(6) # print("Hello World!") # # Resolve math first # print(9 + 6) # # # Combining strings and numbers # print("hi", "there", 9) # print("9 + 6 =", 9 + 6) # print("The answer is", 9 + 6, ".") # # # Optional arguments # print("The answer is ", 9 + 6, ".", se...
a = 3 print(type(a)) print(a) print("========================") b = 3.0 print(type(b)) print(b) print("========================") c = False print(type(c)) print(c) print("========================") d = 5 + 3j print(type(d)) print(d)
import sqlite3 import random class DataBase: connection = None cursor = None def __init__(self): # self.conn = sqlite3.connect('C:\\Users\\aleks\\Documents\\BankVR_server\\DataBase\\BankVR.db') self.conn = sqlite3.connect('/root/BankVR_server/DataBase/BankVR.db') self.cursor = sel...
# -*- coding: utf-8 -*- the_count = [1, 2, 3, 4, 5] fruits = [u'яблоко', u'апельсин', u'персик', u'абрикос'] change = [1, '25', 2, '50', 3, '75'] # цикл for первого типа обрабатывает список for number in the_count: print u"Счетчик %d" % number # то же, что и выше for fruit in fruits: print u"Фрукт: %s" % fruit # ...
# #Basic Fundamentals of Python # #* variables & type dari variablenya # nama = "andi" #string # usia = 12 #integer # tinggi = 189.3 #float # jomblo = False #boolean # # String # #* penjelasan sederhana # print("jum'at") #tanda kutip 1 dengan 2 beda # print('jum\'at') ...
#bikin fungsi yang tugasnya remove duplicate huruf inputUser = input('Masukan nama : ') name = set(inputUser) print(name) nameList = sorted(list(name)) print(nameList) newString = '' for i in inputUser: if i in nameList: i = '*' newString += i else: newString += i print(newString, 'abc...
# nama = 'arian' # print(len(nama) + 10) # print(nama[1:len(nama)]) # print(nama[len(nama) - 1]) # print(nama.replace('a', 'e')) # print(max(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) #mensortir angka terbesar untuk dijadikan sebagai output # print(min(1, 2, 3, 4 ,5, 6, 7, 8, .2)) # print(round(3.6501, 1)) # print(round...
# to print even numbers i = 2 while(i<=20): print(i) i+=2
# for printing pattern 1 rows = 1 numbers = 1 for rows in range(1,6): for numbers in range(1,rows+1): print(numbers, end=" ") print()
a = "123" # string data type b = 10 a = int(a) # it will explicitly convert the provided variable in brackets to the data type written
a = ["A",32,56.3,"N",34.5,12] print(a) # prints the whole list elements print(a[1]) # prints the 1st elements of list
# Implementing an Item Class to hold information about items. Includes names, descriptions, positions, and comabt attributes. class Weapon: """A simple Weapon Class""" def __init__(self, name, description, location, damage, price): self.name = name self.description = description self.lo...
# Given two strings, write a method to decide if one is a permutation of the other # Examples # permu("there", "their") = False # permu("god", "dog") = True def permu(str1, str2): # Check the length of the two strings. if not equal return false. if len(str1) != len(str2): return False # Create ...
""" Имя проекта: practicum-1 Номер версии: 1.0 Имя файла: 1.py Автор: 2020 © В.С. Свежинцев, Челябинск Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru) Дата создания: 11/12/2020 Дата последней модификации: 11/12/2020 Связанные файлы/пакеты: numpy, random Описание: ...
""" Имя проекта: practicum-1 Номер версии: 1.0 Имя файла: 1.py Автор: 2020 © В.С. Свежинцев, Челябинск Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru) Дата создания: 11/12/2020 Дата последней модификации: 11/12/2020 Связанные файлы/пакеты: numpy, random Описание:На...
""" Имя проекта: practicum-1 Номер версии: 1.0 Имя файла: 1.py Автор: 2020 © В.С. Свежинцев, Челябинск Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru) Дата создания: 11/12/2020 Дата последней модификации: 11/12/2020 Связанные файлы/пакеты: numpy, random Описание: ...
print("Hello World") temperature = "14" print(temperature + " degrees") city_name = "Vancouver" province_name = "British Columbia" country_name = "Canada" print(city_name + ", " + province_name + ", " + country_name + ".") number_of_application = 5 + 1 print(number_of_application) percent = 0.5 * 100 print(percent) ...
from decimal import Decimal def isdigit(item:str) -> bool: "Tries to convert the given `item` into an integer using try/except" try: int(Decimal(item)); return True except: return False def format_seconds(delta:int) -> str: "Formats an integer representing seconds, breaking it into days, hours, minute...
units = ("мм", "см", "м", "км") print("Выберите единицу измерения площади прямоугольника:\n") i = 1 for x in units: print("введите {} для выбора {}".format(i, x)); i += 1 print("\nОжидание ответа...") selected_unit = int(input()) while (selected_unit < 0 or selected_unit > 4): print("\nВведены неверные данные. Зна...
from math import sqrt class Complexnumbers: def __init__(self,real,imaginary): self.real = real self.imaginary = imaginary def conjugate(self): self.real = self.real self.imaginary = self.imaginary*(-1) return self def __add__(self, num1): return Comple...
# This is my first python program msg = "hello world" print(msg) # using Python as a calculator num_1 = 6 num_2 = 3 num_3 = int(num_1/num_2) #Typecasting num_4 = float(num_1/num_2) print(num_1 * num_2) print(num_3) print(num_4) print(num_1/num_2) # Floating point numbers float_1 = 12.5 float_2 = 6.3 print( floa...
# Importing the libraries import random import os # Global variables theBoard = {'1':' ', '2':' ', '3':' ', '4':' ', '5':' ', '6':' ', '7':' ', '8':' ', '9':' '} mylist = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] computer_choice = [] # User defined functions def clearScreen(): if os.name == 'posix': #...
""" 82.Remove Duplicates from Sorted List II Difficulty: Medium Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well. Example 1: Input: 1→2→3→3→4→4→5 Output: 1→2→5 Example 2: Input: 1→1→1→2→3 Output...
# With List Comprehension Solutions # ---------------------------------------- # https://edabit.com/challenge/vTGXrd5ntYRk3t6Ma # Solution 1 # def is_isogram(txt): # txt = txt.lower() # for letter in txt: # if txt.count(letter) > 1: # return False # return True # print(is_isogram(...
'''Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. Hint: how does an even / odd number react differently when divided by 2? Extras: If the number is a multiple of 4, print out a different message. Ask the user for two numbers: one number...
'''Write a program (using functions!) that asks the user for a long string containing multiple words. Print back to the user the same string, except with the words in backwards order. For example, say I type the string: My name is Michele Then I would see the string: Michele is name My shown back to me.''...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @File : case_num-count.py @Author: gentle.yu @Date : 2020/8/4 17:26 """ # 输入一个数字并判断是几位数及每个数字出现的次数 a = str(int(input('请输入一个正整数'))) if a.lstrip('-'): lena = len(a) - 1 else: lena = len(a) print('数字{}是{}位数'.format(a, lena)) for i in a: if i == '-': ...
from room import Room from player import Player from items import Item # Rooms outside = Room("Outside Cave Entrance", "North of you, the cabe mount beckons", [('shield')]) foyer = Room("Foyer", "Dim light filters in from the south. Dusty passages run north and east.",[('sword')]) overlook = Room("Grand Overlook", "A ...
class Node: def __init__(self, value): self.value = value self.next = None class LinkedList: def __init__(self): self.head = None self.tail = None def add_to_tail(self, value): new_node = Node(value) if self.head is None: self.head = new_node ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """flatten an array of nested arrays of integers into a flat array of integers """ class Flatten(object): def flatten(self, arr): if arr == []: return arr if isinstance(arr[0], list): return self.flatten(arr[0]) + self.flatten(arr[1:]) r...
def reverse_vowels(s): """Loops through an input string (s) and creates a string of the vowels in it (excluding y). Then reverses the string of vowels and loops through the initial s again, replacing the normal vowels with the reversed vowels. """ vowels_in_string = '' vowels = 'aeiouAEIOU' ...
def two_list_dictionary(keys, values): """Takes as input two lists and creates a dictionary of keys and values from them. If there is no key for the value, ignores the value. If there is no value for the key, provides a key of None. Outputs the dictionary. """ output_dict = {} i = 0 for key i...
def multiply_even_numbers(nums): """Iterates through array and multiplies any even number times the initial newnum. """ newnum = 1 for num in nums: if num % 2 == 0: newnum = newnum * num return newnum
def is_palindrome(phrase): """Checks if input phrase (str) is a palindrome or not. Capitalizes input phrase and removes spaces before checking if input phrase is same forwards and backwards. """ phrase = phrase.upper() phrase = phrase.replace(' ', '') if phrase == phrase[::-1]: retur...
def is_odd_string(word): """Accepts a word as input. For every letter in the word, adds the letters place-value (a = 1, b = 2, c = 3, A = 1, etc.). If the sum of the letters' place-values is odd, returns True, else False. """ output = 0 for letter in word: output = output + ord(f'{letter...
#------------------------------------------------------------------ import random import timeit # Class definitions A = [] ## Define function to make array def randArray(Array, n): for i in range(0, n): Array.insert(i, random.randint(0, 100)) randArray(A, 2000) bstCount = 0 class Node: def ...
from Messages import Messages from Player import Player from Table import Table # For testing purposes from PokerRules import PokerRules from CardStack import CardStack from Deck import Deck from MoneyStack import MoneyStack class Game: """ A Poker Game class. """ def __init__(self):...
#!/usr/bin/env python """ Support code for "Data aggregation" subsection in Chapter 7. Create some artificial data. """ import datetime import pandas as pd import random citymap = { 'Germany': ['Hamburg', 'Munich', 'Berlin', 'Leipzig', 'Frankfurt'], 'UK': ['London', 'Manchester', 'Glasgow', 'Birmingham', 'E...
import numpy as np x = np.random.random(5) print x print x + 1 # add 1 to each element of x
import numpy as np import matplotlib.pyplot as plt colors = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), (44, 160, 44), (214, 39, 40), (148,103,189), (152, 223, 138), (255,152,150), (197, 176, 213), (140, 86, 75), (196, 156, 148), (227,119,194), (247, 182, 210), (127,127,127), (199...
#%% import pandas as pd import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [10, 6] plt.xlabel("Top Items sold") plt.ylabel("Sales in 2017") data = pd.read_csv(r"C:\Users\acer\Downloads\BreadBasket_DMS.csv") data['Date'] = pd.to_datetime(data['Date'],format='%d-%m-%Y', errors='coerce') data['year']...
import numpy as np # Attension: # - Never change the value of input, which will change the result of backward class operation(object): """ Operation abstraction """ def forward(self, input): """Forward operation, reture output""" raise NotImplementedError def backward(self, out_...
"""Inheritance Inheritance is noe of the principles of object-oriented programming. Since classes may share a lot of the same code, inheritance allows a derived class to reuse the same code and modify accordingly """ class Person: def __init__(self, name): self.name = name def get_name(self): ...
"""Permutation related utils.""" from typing import Literal, Mapping, Optional, Union, get_args import numpy as np import skrough.typing as rght from skrough.weights import prepare_weights def get_permutation( start: int, stop: int, proba: Optional[np.ndarray] = None, seed: rght.Seed = None, ) -> n...
"""Unique-related operations. The :mod:`skrough.unique` module delivers helper functions for unique-related computations. Currently all operations are simple wrappers around :func:`numpy.unique` but they are here to provide interfaces that the rest of the code uses. """ from typing import Tuple import numpy as np ...
def computeFraction( poi_messages, all_messages ): """ given a number messages to/from POI (numerator) and number of all messages to/from a person (denominator), return the fraction of messages to/from that person that are from/to a POI """ if poi_messages == "NaN": ...
# -*- coding: utf-8 -*- """ Created on Tue Feb 19 14:31:24 2019 @author: Rajesh Samui """ class BuiltInType: """ Built in Types """ def __init__(self): pass def boolean_test(self, *args, **kwargs): """ Here are most of the built-in objects considered false: con...
#Shortest possible substring contains all alphabets present in string def short_string(s): print len(s) substring=[] dict={} for i in range(len(s)): if dict.get(s[i])==None: dict[s[i]]=dict.get(s[i],0)+1 for j in range(i+1,len(s)+1): substring.append(s[i:j]) m...
tuna="Fish" if tuna=="bass": print ("this is a fish alright") elif tuna=="Fish": print ("this is a fish alright") else: print ("I don't know what is this")
from random import shuffle class Deck: cards = [10]*2*4 + list(range(1,10))*4 + ['As']*4 def shuffle_deck(self): shuffle(self.cards) return self.cards def draw(self, number_of_cards=1): cards_given = [] for n in range(1, number_of_cards+1): ...
message = "Hello World" for s in message: print(s) message = [s + " " for s in message] print(''.join(message)) #(which joins list of charecter to string) print('*'.join(message))
#Raise statement demo def printbox(symbol,legnt,hight): if len(symbol) != 1: raise Exception ('Symbol needs to a string of lenght 1') if legnt<2 & hight<2: raise Exception('Legnth and hight should be greater than 2') print(symbol * legnt) for i in range(hight-2): prin...
####################################### # ASSIGNMENT 3 # # AIT-590, Summer 2021 # # Group 3: Fernando, Melissa, Archer # # July 7, 2021 # # # # Assuming you have python 3 # # TO EXECUTE RUN: # ...
# comparison.py userAge = int(input("enter your age:")) if userAge > 10 and userAge < 13: print("youre a tween") if userAge <= 10: print("you are babby") if userAge >= 13 and userAge <= 19: print("youre a teenager") else: print("you're old")
# 3. 模型定义和操作 # convolutional neural network (2 convolutional layers) class ConvNet(nn.Module): def __init__(self, num_classes=10): super(ConvNet, self).__init__() self.layer1 = nn.Sequential( nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2), nn.BatchNorm2d(16), ...
import torch.nn as nn from receptivefield import receptivefield if __name__ == '__main__': # define a network with different kinds of standard layers net = nn.Sequential( nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3), nn.BatchNorm2d(num_features=32), nn.ReLU(), nn.MaxPool2d(kernel_siz...
from keras.engine import Layer from keras.layers import Conv2D, BatchNormalization def convolution_block(input_layer: Layer, filters: int, name: str, kernel_size: int = 3, activation: str = 'relu', amount: in...
import requests import json import os from dotenv import load_dotenv import json import pprint as p load_dotenv() API_key = os.getenv('WEATHER_API') print(API_key) API_URL = "https://api.openweathermap.org/data/2.5/" #Helper function def kelvin_to_celsius(number): kelvin = 273.15 number = float(number) r...
children=['chochlate','wafers','pizza','pencil','toffee','kurkure','chartpaper','biscuit'] adults=['chochlate','pizza','juice','pen','pencil','biscuit','chartpaper'] man=['juice','biscuit','namkeen','pen','sheets','file','briefcase'] woman=['juice','biscuit','namkeen','sanitizers','soap','washing powder','pen'] print("...
def isprime(n): for i in range(2,int(n/2)+1): if n % 2 == 0: return False return True def prime_factors_gen(n, d): d_ = d if n == 1: return d_ elif n % 2 == 0: if 2 in d_.keys(): n = n / 2 d_[2] = d_[2] + 1 #print(d_) e...
for i in range(int(input())): a,b=input().split() a=int(a) b=int(b) m=a if a<b: m=b print(m," ",(a+b))
def sort(my_list): size = len(my_list) for i in range(size): for j in range(size-i-1): if(my_list[j] > my_list[j+1]): tmp = my_list[j] my_list[j] = my_list[j+1] my_list[j+1] = tmp numbers=([]) amount=input("How many numbers are in your list? "...
n=int(input()) for i in range(n): b=int(input()) if b<1500: salary=float(2*b) else: salary=float(500+1.98*b) print(salary)
def comparing_lists(): print (""" 7) Dadas dos listas, debes generar una tercera con todos los elementos que se repitan en ellas, pero no debe repetise ningún elemento en la nueva lista: """) print ("---") a=(list(range(0,31,3))) print ("A list is --> ", a) b=(list(range(0,31,2))) print ("B list is --> ",...
import math print (""" 2) Realiza una función llamada area_circulo() que devuelva el área de un círculo a partir de un radio. Calcula el área de un círculo de 5 de radio: areaCirculo=(radio**2)*pi Puedes utilizar el valor 3.14159 como pi o importarlo del módulo math: import math print(math.pi) > 3.1415... """) de...
print (""" Argumentos y parámetros indeterminados: Quizá en alguna ocasión no sabemos de antemano cuantos elementos vamos a enviar a una función. En estos casos podemos utilizar los parámetros indeterminados por posición y por nombre. """) print (""" \nPor posición: Para recibir un número indeterminado de parámetros...
print (""" Funciones recursivas: Se trata de funciones que se llaman a sí mismas durante su propia ejecución. Funcionan de forma similar a las iteraciones, y debemos encargarnos de planificar el momento en que una función recursiva deja de llamarse o tendremos una función rescursiva infinita. Suele utilizarse para ...
print (""" 1) Realiza una función llamada area_rectangulo() que devuelva el área del rectangulo a partir de una base y una altura. Calcula el área de un rectángulo de 15 de base y 10 de altura. """) def area_rectangulo(base,altura): return (base*altura) res=area_rectangulo(15,10) print ("El área de rectangulo de ba...
def numeros(a,b): # print ("Los argumentos de la función son: 12 y 5") suma = 12+5 print ("Suma 12+5: "+str(suma)) resta = 12-5 print ("Resta 12-5: "+str(resta)) multiplicacion = 12*5 print ("Multiplicación 12*5: "+str(multiplicacion)) division = 12/5 print ("División 12/5: "+str(division)) modulo = 12...
# 5) La siguiente matriz (o lista con listas anidadas) debe cumplir una condición, y es que en cada fila, el cuarto elemento siempre debe # ser el resultado de sumar los tres primeros. # (La función llamada 'sum(lista)' devuelve una suma de todos los elementos de la lista) #matriz = [ # [1, 1, 1, 3], # [2, 2...
# 4) A partir del ejercicio anterior, vamos a suponer que cada número es una nota, y lo que queremos es obtener la nota media. El problema # es que cada nota tiene un valor porcentual: # # La primera nota vale un 15% del total # La segunda nota vale un 35% del total # La tercera nota vale un 50% del total # Desarroll...
print (""" 1. Crea una clase llamada Punto con sus dos coordenadas X e Y. 2. Añade un método constructor para crear puntos fácilmente. Si no se reciben una coordenada, su valor será cero. 3. Sobreescribe el método string, para que al imprimir por pantalla un punto aparezca en formato (X,Y) 4. Añade un método...
print (''' ## Higher order functions and list comprehensions: 30. Represent a small bilingual lexicon as a Python dictionary in the following fashion {"merry":"god", "christmas":"jul", "and":"och", "happy":gott", "new":"nytt", "year":"år"} and use it to translate your Christmas cards from English into Swedish. ...
print (""" 4) Realiza una función llamada intermedio() que a partir de dos números, devuelva su punto intermedio: Nota: El número intermedio de dos números corresponde a la suma de los dos números dividida entre 2 Comprueba el punto intermedio entre -12 y 24 """) def intermedio(a,b): return (a+b)/2 res=intermed...
def media(): print ("Please enter the first note: ") note_1 = int(input()) print ("Please enter the second note: ") note_2 = int(input()) print ("Please enter the third note: ") note_3 = int(input()) average = (note_1 + note_2 + note_3)/3 print("The average score is :", average) print ("---") print ("This ...
# python # Returns a flat list of all the values in a flat dictionary # we can use values() funciton to get all values in dictionary # then using list() function, we can make it as a list def valuesList(dictionary): return list(dictionary.values()) ages = { "eunbae":100, "soojeong":103, "yea":99, } ...
#python # There is one ATM. # There are N people infront of the ATM # The sum of the time to get the money depends on the order in which people line up. n = int(input()) list = list(map(int, input().split())) def minTime(n, list): list.sort() # The return value of sort() : None sum = 0 for i in range(n): ...
# phthon # Returns all elemetns in a list except for the first one. def exceptFirstOne(list): if len(list) >1: return list[1:] else: return list #or simply, we can code : return list[1:] if len(list) > 1 else list print(exceptFirstOne([1,2,3,4])) print(exceptFirstOne([1]))
# python # Returns True if there are duplicate values in a flat list, False otherwise. from collections import Counter def IsDuplcate(list): count_values = Counter(list) print(count_values) for i,z in count_values.items(): if z>1: return True return False x = [1,2,3,4,4,5,6,7] y = ...
# python # Converts Celsius to Fahrenheit # the formula : Fahrenheit = (Celsius * 1.8) +32 def convertToFahrenheith(celcius): return (celsius * 1.8) + 32 celsius = 200 print("Celsius", celsius, "is ", convertToFahrenheith(celsius), " in Fahrenheit!")
# python # Converts a number to a list of digits def convertListOfDigits(num): res = [int(x) for x in str(num)] return res a = 12345 print("Make ", a , "into a list of digits: ", convertListOfDigits(a)) # We can use map() # def convertListOfDigits(num): # return list(map(int,str(num)))
import io from itertools import permutations string = 'abcdefgh' target_string = 'fbgdceah' instructions = [] file = open('input.txt', 'r') for line in file: inst = [] if 'swap position' in line: inst.append('swap_position') inst.append(int(line.split()[2])) inst.append(int(line.split(...
import io directions = [] current_x = 0 current_y = 0 current_direction = 'north' file = open('input.txt', 'r') for line in file: for dir in line.strip().split(', '): directions.append((dir[0], int(dir[1:]))) def turn(cur_dir, turn_dir): if turn_dir == 'L': if cur_dir == 'north': ...
import random random_num = random.randint(1,100); guessing_count=0 guess=0 while (guess != random_num): guess = int(input("Enter your guess between 1 to 100 :")); if (random_num>guess): if(random_num-guess<=10): print("Your guess is slightly less than the number. Keep guessing") els...
#!/usr/bin/env python3 # Author: Nandika Shendre # Importing boto3 library import boto3 # Taking input for region name from user region = input("Enter the region: ") # Use default value 'us-west-2' # If region not entered by user # Using boto library # Retrieving ec2 instances with the region input ec2 = boto3.r...
# Write a recursive function that takes one parameter: n and adds numbers from 1 to n. def sum(n): if n == 0: return 0 else: return n + sum(n - 1) print(sum(3))
class Person(): def __init__(self, name): self.name = name self.hunger = 10 def greet(self, other): return f"Hello, {other.name}!" def is_hungry(self): return self.hunger > 5 def eat(self, amount = 1): self.hunger -= amount def __str__(self): r...
import random class DiceSet(object): def __init__(self): self.dices = [0, 0, 0, 0, 0, 0] def roll(self): for i in range(len(self.dices)): self.dices[i] = random.randint(1, 6) return self.dices def get_current(self, index = None): if index != None: ...
# Write a program that asks for two numbers and prints the bigger one num1 = int(input("Please input the first number: ")) num2 = int(input("Please input the second number: ")) if num1 > num2: print(f"{num1} is bigger!") else: print(f"{num2} is bigger!")
# Write a program that asks for an integer that is a distance in miles, # then it converts that value to kilometers and prints it mile = input("Please enter the miles to convert: ") kilo = float(mile) * 1.6 print (f"{mile} miles in kilometers is {kilo}.")
# - Create a variable named `base_num` and assign the value `123` to it # - Create a function called `doubling` that doubles it's input parameter and returns with an integer # - Print the result of `doubling(base_num)` base_sum = 123 def doubling(value): return value * 2 print(doubling(base_sum))
# Given a string, compute recursively (no loops) a new string # where all the lowercase 'x' chars have been changed to 'y' chars. def strings(string): if string == "": return string else: if string[0] == "x": return strings("y" + string[1:]) else: return string[...
# Write a program that reads a number from the standard input, then draws a # square like this: # # # %%%%%% # % % # % % # % % # % % # %%%%%% # # The square should have as many lines as the number was num = int(input("Please input an integer number: ")) for i in range(1, num + 1): if i == 1 or i == nu...
tel_book = {"William A. Lathan": "405-709-1865", "John K. Miller": "402-247-8568", "Hortensia E. Foster": "606-481-6467", "Amanda D. Newland": "319-243-5613", "Brooke P. Askew": "307-687-2982"} #print(tel_book["John K. Miller"]) def findNumber(name): if "name" in te...
class Animal(): def __init__(self, hunger = 50, thirst = 50): self.hunger = hunger self.thirst = thirst def eat(self): self.hunger -= 1 def drink(self): self.thirst -= 1 def play(self): self.hunger += 1 self.thirst += 1 puppy = Animal() puppy.eat()...
class BlogPost(): def __init__(self, author_name, title, text, publication_date): self.author_name = author_name self.title = title self.text = text self.publication_date = publication_date blog1 = BlogPost("John Doe", "Lorem Ipsum", "Lorem ipsum dolor sit amet.", "2000.05.04.") blo...
list_money = [500, 1000, 1250, 175, 800, 120] def sum(money): sum = 0 for i in range(len(money)): sum += money[i] return sum def greatest(money): reserved_money = 0 for i in range(len(money)): current_val = money[i] if reserved_money < current_val: reserved_mone...
from mymath import add import unittest class TestMyMathMethods(unittest.TestCase): def test_add_with_positive_integers(self): actual = add(2, 3) expected = 5 self.assertEqual(actual, expected, "2 + 3 must be 5") self.assertEqual(add(5, 5), 10) def test_add_with_negative_floats(...
""" 本节定义二分法查找算法: 1,二分法查找针对的查找对象是有序的; 2,二分查找同样返回布尔值; """ def erfenquery(object, value): first = 0 last = len(object) - 1 found = False while first <= last and not found: midpoint = (first + last) // 2 if midpoint == value: found = True else: if midpoint < ...