text
stringlengths
37
1.41M
# Modify the code inside this loop to stop when i is greater than zero and exactly divisible by 11 # for i in range(0, 100, 11): # if i % 11 == 0: # break # print(i) for i in range(0, 100, 7): print(i) if i > 0 and i % 11 == 0: break
vehicles = {'dream': 'Honda 250T', # 'roadster': 'BMW R1100', 'er5': 'Kawasaki ER5', 'can-am': 'Bombardier Can-Am 250', 'virago': 'Yamaha XV250', 'tenere': 'Yamaha XT650', 'jimny': 'Suzuki Jimny 1.5', 'fiesta': 'Ford Fiesta Ghia ...
def multiply(x: float, y: float) -> float: """ Multiply 2 numbers. Although this function is intended to multiply 2 numbers, you can also use it to multiply a sequence. If you pass a string, for example, as the first argument, you'll get the string repeated `y` times as the returned val...
data = [4, 5, 104, 105, 110, 120, 130, 130, 150, 160, 170, 183, 185, 187, 188, 191, 350, 360] # del data[0:2] # print(data) # del data[16:] # print(data) # del data[14:] # print(data) min_valid = 100 max_valid = 200 for index, value in enumerate(data): if (value < min_valid) or (value > max...
revenue = float(input("Введите выручку Вашей фирмы: ")) expenses = float(input("Введите затраты Вашей фирмы: ")) if revenue > expenses: print("Ваша фирма прибыльная!") profitability = (revenue - expenses) / revenue print((f"Рентабельность Вашей фирмы - {profitability}")) staff = int(input("Введите колич...
class Road: def __init__(self, lenght, width, a, m): self._lenght = lenght self._width = width self.a = 5 # толщина асфальта self.m = 25 # масса асфальта для покрытия 1 кв.м def calc(self): print(f"{(self._lenght * self._width * self.a * self.m) / 1000}т") total = Road(...
def division(a, b): try: return a / b except ZeroDivisionError: return print('Делить на ноль нельзя!') print(division(6, 0))
my_list = [1, 2, 3, 2, 3, 5, 6, 5, 8, 9, 11, 123, 321, 123, 0] new_list = [i for i in my_list if my_list.count(i) == 1] print(new_list)
n = int(input("Введите целое положительное число, а я найду самую большую цифру в нем: ")) max = 0 while n > 0: a = n % 10 if a == 9: max = a break elif a > max: max = a n = n // 10 print(max)
from copy import deepcopy """ 时间复杂度 n^n """ def maxSizeSlices(slices): if len(slices) <= 3: return max(slices) maxPiza = 0 dp = [] dp.append((slices, 0)) while len(dp) > 0: slices, currentPiza = dp.pop() if len(slices) <= 3: maxPiza = max(maxPiza, (max(slices) + ...
t=int(input()) while(t>0): n=int(input()) print(n) t=t-1
### DICTIONARIES product = { "name" : "Book", "quantity" : 1, "price" : 4.99 } person = { "firstName" : "Joan", "lastName" : "Perez Alvarado" } ## accesing keys #print(person['firstName']) # delete object ## del person; ## Working with keys print(person.keys()); print(person.items()); ## Cleari...
import random # Making A General GCD function def gcd(num1,num2): if num2 == 0: return num1 else: return gcd(num2,num1%num2) # 1. Picking a large random integer number. n = random.randint(1,10000) while gcd(n,2310)!= 1: n = random.randint(1,10000) print("Random Number (n): "+str(n)) # ...
EOL = '\n' # end of line character MAX = 1024 # maximum number of bytes to receive at a time # The Receiver class manages receiving messages over a socket class Receiver: def __init__(self, sock): # The socket instance variable stores the socket associated with # the receiver which is pa...
""" Functions for preprocessing mortgage complaints data. """ import pandas as pd def encode_targets(df, target_column, target_encoding_dict): """ Replaces values in `df` target_column with the corresponding values specified in the encoding_dict Parameters ---------- df : pandas.DataFram...
import time from turtle import Turtle class Bullet(Turtle): def __init__(self, position): super().__init__() self.shape('circle') self.color('red') self.bullets = [] self.hideturtle() self.shapesize(0.5) self.penup() self.goto(position) self.f...
# write your code here from random import randint, choice import os class Calculator: def __init__(self): self.difficulty = None self.level_descriptions = ["simple operations with numbers 2-9", "integral squares of 11-29"] self.choose_difficulty() self.task_generator = Calculator.T...
""" Miranda Lassar and Sonia Presti and Charisma Chauhan storybook_app.py is an app for stories in the terminal it is also used as a module in the storybook_webapp flask app """ def split(word): return list(word) def welcome(name): newName = split(name) for y in range(0, len(newName)): if newNam...
""" Question 2 """ class BinarySearchTreeMap: class Item: def __init__(self, key, value=None): self.key = key self.value = value class Node: def __init__(self, item): self.item = item self.parent = None self.left = None s...
""" Question 5 """ class ArrayStack: def __init__(self): self.data = [] def push(self, item): self.data.append(item) def pop(self): return self.data.pop() def top(self): return self.data[-1] def __len__(self): return len(self.data) def isEmpty(self): ...
from collections import Counter, defaultdict f=open("1661.txt","r") def getTotalNumberOfWords(): #f=open("1661.txt","r") f=open("1661.txt","r") count=0 for line in f: for word in line.split(): count+=1 print("total number of words:",count) def getTotalUniqueWords(): ...
s=input() print(s) s=input("Enter your name: ") print(s) i=int(input("Enter an integer:")) print(i) print(type(i)) lst = [int(x) for x in input("Enter 3 numbers: ").split()] print(lst)
import math radius=float(input("Enter radius")) area = math.pi*radius**2 print(area)
a,b,c = [int(x) for x in input("Enter 3 numbers").split()] average = (a+b+c)/3 print("Average of 3 numbers is ",average)
x=int(input("Enter min number")) y=int(input("Enter max number")) i=x if(i%2==0): i+=1 while(i<=y): print(i) i+=2
# https://leetcode.com/problems/fizz-buzz/ def fizz_buzz(n): # do a for loop result = [] for i in range(1, n+1): if i % 3 == 0 and i % 5 == 0: result.append('FizzBuzz') elif i % 3 == 0: result.append('Fizz') elif i % 5 == 0: result.append('Buzz') ...
# https://leetcode.com/problems/factorial-trailing-zeroes/ # 1! = 1 # 2! = 2*1 = 2 # 3! = 3*2*1 = 6 # 4! = 4*3*2*1 = 24 # 5! = 5*4*3*2*1 = 120 - one trailing zero # 6! = 6*5*4*3*2*1 = 720 - one trailing zero # 7! = 7*6*5*4*3*2*1 = 5040 - two trailing zeros # how many multiples of 5 in a given n? import math def trail...
# https://leetcode.com/problems/number-of-segments-in-a-string/ def count_segments(s): return len(s.split()) print(count_segments('Hello, my name is John'))
# https://leetcode.com/problems/defanging-an-ip-address/ def defang_ip(address): result = [] for char in address: if char == '.': char = '[' + char + ']' result.append(char) return ''.join(result) print(defang_ip('1.1.1.1'))
# https://leetcode.com/problems/move-zeroes/ def move_zeros(arr): # do it in place i = 0 for j in range(len(arr)): if arr[j] != 0: arr[i], arr[j] = arr[j], arr[i] i += 1 return arr print(move_zeros([0, 1, 0, 3, 12])) # O(n) - time complexity # O(1) - space complexity
# Given a non-empty string s, you may delete at most one character. Judge # whether you can make it a palindrome. # Input: "aba" # Output: True # # Input: "abca" # Output: True # Explanation: You could delete the character 'c'. # brute force solution is to delete each char and see if the rest of the s is a panlindrom...
# https://leetcode.com/problems/implement-strstr/ def strStr(haystack, needle): L = len(haystack) n = len(needle) for i in range(L): if haystack[i:n+i] == needle: return i return -1 print(strStr('hello', 'll'))
def update_path_with_transfer_count(all_paths, trips): """ Takes all paths list with dictionary and updates them with transfers needed from trips """ for paths in all_paths: for path in paths.values(): path["transfers"] = get_transfer_count(path["path"], trips) def get_transfer_...
#deleting the repetetive characters a = 'Biiiishwwwwa' new_string = '' for i in range(len(a)): if i != len(a) -1 and a[i+1] == a[i]: pass else: new_string += a[i] print new_string
# 注意一定要按照这个模板格式,不然报错,特别注意冒号:和缩进问题 print('请输入一个1-100之间的数字') str = input() num = int(str) if num < 60: print("您的分数不及格") elif num < 70: print("合格") elif num < 80: print("中等") elif num < 90: print("良好") else: print("优秀") # if x: # print('True') # 只要x是非零数值、非空字符串、非空list等,就判断为True,否则为False
# print('Início') # for num in range(0, 6): # print(num) # if num == 2: # break # print('Final') # for c in 'Curso de Python': # print(c) # if c == 'o': # break # for c in 'Curso de Python': # if c == 'o': # continue # print(c) # for c in 'Curso de Python': # if c ...
# n1 = 1 # n2 = 0 # soma = n1 + n2 # # while soma > 0: # n1 = int(input('Número 1: ')) # n2 = int(input('Número 2: ')) # soma = n1 + n2 # print(f'{n1} + {n2} = {soma}\n') numero = 7 while numero >= 3: print(numero) numero = numero - 1
num = [1,2,3,4,5] print(num) # # num.append(10) # print(num) # # num.insert(0,20) # print(num) # num.insert(3, 50) num.insert(-1, 80) print(num) # num[1] = 'D' # num[2] = 'p' # print(num) # del(num[1]) # print(num) # del(num[2:4]) # print(num) # num.clear() # print(num) # num = [1,2,3,4,5] # print(num) # print(num...
import sys import os # https://www.geeksforgeeks.org/merge-sort/ def merge(input_array, left, middle, right): comps = 0 N1 = middle - left + 1 N2 = right - middle left_sub = [] right_sub = [] for i in range(0, N1): left_sub.append(input_array[left + i]) for j in range(0, N2): ...
# -*- coding: utf-8 -*- """ Created on Wed Apr 10 12:47:09 2019 @author: Saloni Rawat """ from numpy import random import tictactoe gameBoard = tictactoe.create_board() tictactoe.print_board(gameBoard) Players = (tictactoe.PIECE_ONE, tictactoe.PIECE_TWO) def HumanPlayer(board, history, players): ...
# copy(): 深拷贝字典,创建一个新的字典对象。 name_dict = {"name": "python", "age": 26, "id": 110} # pop():参数是键,删除指定的键值对,并返回值(第二个参数表示如果没有这个键值队,则返回这个值) print(name_dict) newName_dict = name_dict.copy() print(newName_dict) newName_dict.pop("name") print(newName_dict) INFO = newName_dict.pop("newName", "没有这个键") # 有这个键就删除这个键,没有就返回第二个参数的值...
# coding=utf-8 card_info_save = [] def add_card_info(): name_info = input("请输入姓名:") age_info = input("请输入年龄:") sex_info = input("请输入性别:") card_info_save.append([name_info, age_info, sex_info]) print(card_info_save) print("[INFO]:用户信息存储成功") def del_card_info(): del_name = input("请输入要删除的用户...
# 1、创建集合 """ 集合里的数据是唯一的,没有重复的数据 集合、列表、元组 可以互相转换 交集& 并集|(会去重) 差集 - """ num_set = set() # 集合 print(type(num_set)) num_set1 = (1, 2) # 元组 print(type(num_set1)) num_list = [10, 20, 30, -90] print(max(num_list)) print(min(num_list))
# coding=utf-8 import os file_path = os.getcwd() file_name_list = os.listdir(file_path) print(file_name_list) my_file = input("请输入要查询的文件名:") # for my_file_list in file_name_list: if my_file not in file_name_list: print("[ERROR:]not found the file 'my_file'") else: postion = my_file.rfind(".") newfile_name ...
import random number1 = random.randint(1, 1000) counter = 1 number2 = random.randint(1, 1000) while number1 != number2: counter += 1 number2 = random.randint(1, 1000) print('number 1 is:', number1) print('number 2 is:', number2) print('number of attempts:', counter)
list_noun = ['dog', 'potato', 'meal', 'icecream', 'car'] list_adj = ['dirty', 'big', 'hot', 'colorful', 'fast'] for x in list_adj: for z in list_noun: print(x, z)
import random dice_range = range(1, 6) dice = random.choice(dice_range) if dice == 1: print('o') elif dice == 2: print('\to \no') elif dice == 3: print('\t\to\n\to\no') elif dice == 4: print('o o') print(' ') print('o o') elif dice == 5: print('o o') print(' o ') print('o o') else:...
a=int(input("enter value ")) sum=0 num=1 while a>0: r=a%10 sum=sum+r num=num*r a=a//10 print("sum",sum) print("num",num) if sum==num: print("twin") else: print("not twin")
a=int(input("enter value of a : ")) b=int(input("enter value of b : ")) if a>b: print("a moto che") else: print("b moto che")
a=int(input("enter value ")) no=a rev=0 while a>0: r=a%10 rev=(rev*10)+r a=a//10 print("rev",rev) if no==rev: print("pelindrom") else: print("not pelindrom")
# -*- coding: utf-8 -*- """ Created on Tue Apr 21 14:38:50 2020 @author: jyoth """ #It is a binary classification # Importing the datasets import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Social_Network_Ads.csv') X = dataset.iloc[:, ...
# # 1 # def acc(x): # for y in range(x,0,-1): # print(y) # acc(10) # # 2 # def printReturn(x,y): # print(x) # return(y) # z=printReturn(10,5) # print(z) # # 3 # def length(x): # sum=len(x)+x[0] # return sum # z=length([1,2,3,4,5]) # print(z) # # 4 # def valGreat2(x): # y=[] # for i i...
import random def randInt(min=0, max=100 ): num= random.random() *(max-min)+min num=round(num) return num print(randInt(max=50))
import random while True: choices = ["pedra","papel","tesoura"] computer = random.choice(choices) player = None while player not in choices: player = input("Pedra, papel ou tesoura?").lower() if player == computer: print("O computador escolheu", computer) print...
__author__ = 'satish' # We have a class defined for vehicles. # Create two new vehicles called car1 and car2. Set car1 to be a red convertible # worth $60,000 with a name of Fer, and car2 to be a blue van named Jump worth $10,000. # define the Vehicle class class Vehicle: name = "" kind = "car" color = "" ...
import time condition = 0 #this while loop adds one to the condition variable so it no longer meets the condition to run the loop again #so the loop ends while condition == 0: print("the variable 'condition' is equal to 0") condition += 5 print("the variable 'condition' is no longer equal to 0 so the loop i...
snt=input() snt=snt.lower() x=[] for i in snt: if i.isalpha(): x.append(i) x=set(x) if len(x)==26: print("Pangram") else: raise ValueError("Not a pangram")
""" Assume you are given two dictionaries d1 and d2, each with integer keys and i nteger values 1. find interesection 2. find difference Source: MIT excercise author: Akshit Gupta """ #Let's take two dictionaries #Hard coding the dictionaries # d1 = {1:10,2:20,3:30,5:80} # d2 = {1:40, 2:50, 3:60, 4:40, 6:70, 7:80} ...
""" Class Inhertiance Program author: Akshit Gupta <akshitgupta29@gmail.com> """ class Coin: def __init__(self, rare=False, clean=True, head=True, **kwargs): for key,value in kwargs.items(): setattr(self, key, value) self.is_rare = rare self.is_clean = clean self.head =...
import sys import os import datetime from peewee import * welcome = '\n***Welcome to Work Database for Python Command Line***\n' db = SqliteDatabase('tasks.db') class Task(Model): employee = CharField(max_length=100) name = CharField(max_length=100) time = IntegerField(default=0) dat...
word="ABCDBCA" for char in word: print(char) dic={} for char in word: if(char not in dic): dic[char]=1 else: print("first recursive character",char) break
lst=[(i,"even") if i%2==0 else (i,"odd") for i in range(1,51)] print(lst)
a=(input('enter string')) print(a) for st in a: if st=='l': print(st)
lst=[100,200,39,43,22,12,65,44,73] print("original list is",lst) length=len(lst) print("length of list is",length) i=0 j=0 for i in range(length): for j in range(i+1,length): if(lst[i]>lst[j]): temp=lst[i] lst[i]=lst[j] lst[j]=temp print("sorted list is",lst) print("second...
class Person: def details(self,name,age,gender): self.name=name self.age=age self.gender=gender def printdet(self): print(self.name) print(self.age) print(self.gender) class Actor(Person): def det(self,industry,role): self.industry=industry sel...
#print 1 to 50(normal method) # lst=[] # for i in range(1,51): # lst.append(i) # print(lst) #using list comprehension lst=[i for i in range(1,51)] print(lst)
lim=int(input("enter limit:")) i=1 while(i<=lim): sum=i+(i+1) i+=1 print("sum is",sum)
class Person: def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender def printdet(self): print(self.name) print(self.age) print(self.gender) class Student(Person): def __init__(self, roll_no,mark,name,age,gender): ...
lst=[12,3,1,6,55,76,55] print(lst ) lst.sort() element=int(input("enter the element to b searched:")) #print(lst) flag=0 low=0 upp=len(lst)-1 while(low<=upp): mid=(low+upp)//2 if (element>lst[mid]): low=mid+1 elif (element<lst[mid]): upp=mid-1 elif (element==lst[mid]): flag=1 ...
# Importujemy bibliotekę, która pozwoli nam generować losowe liczby import random # Wczytujemy od użytkownika liczbę rzutów kością, które mamy zasymulować ile_razy = int(input("Podaj ilość rzutów kostką: ")) # Będziemy zliczać, ile razy wypadła wartość 6 # Zliczanie zaczynamy od zera szostki = 0 # W pętli od 0 do li...
class GeometricSequence: """ Implementation of geometric sequence Formula of geometric sequence: an = a1 * r^(n-1) an - nth element of sequence a1 - first element r - common ratio You can get value of element using [] operator Example: seq = GeometricSequence...
class Edge: """Represents edges of graph Atributes --------- start : str beginning of edge end : str ending of edge cost : float distence between start and end """ def __init__(self, start: str, end: str, cost: float): self.start = start self.end ...
for i in range(int(input("How many hello world, do you need? Please use a number:\n"))): print("Hello World!")
# -*- coding: utf-8 -*- """ Created on Fri Jan 8 20:04:37 2021 @author: User """ def f02_13_removeDupl2D(l): """ Removes duplicates from a 2-D list Parameters ---------- l : list 2-dimensional list (list of lists) Returns ------- list 2-D list with the duplicate...
# -*- coding: utf-8 -*- """ Created on Fri Jan 8 20:04:37 2021 @author: User """ def f02_12_evenFromList(l): """ Returns even numbers from the list of integers. Parameters ---------- l : list List of integers (can be empty) Returns ------- list List of the even ...
# -*- coding: utf-8 -*- """ Created on Mon Jan 25 10:26:34 2021 @author: User """ def f03_14_genInterlaced(m, n): """ Generates an interlaced array of int chunks. Parameters ---------- m : int Number of integers in the chunk. n : int Number of chunks Returns -----...
# -*- coding: utf-8 -*- # D10 (14) posortuje słownik według klucza. def d10(dic): return dict(sorted(dic.items())) D = {'Olo': 23, 'Bolo': 34, 'Ala': 20, 'Ela': 15} print(d10(D))
# -*- coding: utf-8 -*- # L36 Napisać funkcję, która wyróżni kolorami czerwonym i zielonym odpowiednio największa # i najmniejszą liczbę w danym łańcuchu. (html: x ) Zasady podobne jak w L34 Przykład: # in: '1 dzielone przez 8 daje 0.128 a 7 dzielone przez 2 daje 3.5' # out: '1 dzielone przez 8 daje 0.128 a 7 dzielone ...
# -*- coding: utf-8 -*- # L2 (2) pomnoży wszystkie elementy na danej liście. def l2(lst, m): return [i * m for i in lst] print(l2([1, 2, 3, 4], 3))
# -*- coding: utf-8 -*- """ Created on Tue Jan 5 14:49:24 2021 @author: Huber Mucha """ def f02_02_removeDuplicates(x): """ Removing duplicates from the input list Parameters ---------- x : list list of numbers or strings (can be empty) Returns ------- list list wi...
# -*- coding: utf-8 -*- # L13 (19) zwróci w postaci listy różnicę między dwiema podanymi listami. def l13(lst1, lst2): return [e1 - e2 for e1, e2 in zip(lst1, lst2)] lista1 = [1, 2, 3, 4, 5] lista2 = [-1, 2, 3, -4, 5] print(l13(lista1, lista2))
import yfinance_ez as yf import streamlit as st import pandas as pd st.title(""" Stock Price app """) st.write(""" This app shows the closing price and the volume of a given ticker symbol """) ticker_symbol = 'TSLA' # This downloads some of the data from the ticker symbol ticker_data = yf.Ticker(ticker_symbol) #...
#!/usr/bin/env python # coding: utf-8 # In[4]: n = int(input("Enter a number: ")) sum = 0 temp = n while temp > 0: Number = temp % 10 sum += Number ** 3 temp //= 10 print(sum) # In[6]: n=int(input("Enter a no:- ")) sum=0 for i in range(0,n+1): sum=sum+i print(sum) # In[7]: n=i...
def calcBMI(): h = float(input("你的身高(cm): ")) w = float(input("你的體重(kg): ")) bmi = w / ((h/100)**2) result = "正常" if 18 < bmi <= 23 else "過高" if bmi > 23 else "過低" print("身高: %.1f cm 體重: %.1f kg BMI: %.2f (%s)" % (h, w, bmi,result)) def menu(): print("BMI計算系統") print("----------") pri...
import random as r print("比骰子") flag = input("比大還是比小(比大請輸入 1, 比小請輸入 0)") user = r.randint(1, 6) + r.randint(1, 6) + r.randint(1, 6) pc = r.randint(1, 6) + r.randint(1, 6) + r.randint(1, 6) if flag == 1: winner = "玩家" if user > pc else "電腦" else: winner = "玩家" if user < pc else "電腦" result = "比{0}, 玩家點數:{1} 電腦點數...
import os import contextlib import sys import re import json def read_json(path, prefix=None): """ Read a Json File a returns a dict It removes comments specified by # before parsing the file. If the json file has a field with a string "py:..." it assumes that it is a python statement and evaluat...
def return_10(): return 10 def add(first_number, second_number): sum = first_number + second_number return sum def subtract(first_number, second_number): sum = first_number - second_number return sum def multiply(first_number, second_number): sum = first_number * second_number return sum ...
# -*- coding: utf-8 -*- import time import sqlite3 from sqlite3 import Error database = "/home/playps/bot/ps_unity.db" def create_connection(db_file): """ create a database connection to a SQLite database """ try: conn = sqlite3.connect(db_file) return conn except Error as e: wit...
class Solution: # @param A : list of integers # @param B : list of integers # @return an integer def coverPoints(self, A, B): step = 0 for i in range(len(B)-1): step = step+max(abs(A[i+1]-A[i]), abs(B[i+1]-B[i])) return step # (x,y) to # (x-1, y-1), # (x-...
jaffa_cakes = 1.00 toilet_roll = 0.50 askProduct = input("What product would you like to buy? ") if askProduct == 'jaffa cakes': print("You will get ", jaffa_cakes / 0.2, "clubcard points for your", askProduct) elif askProduct == 'toilet roll': print("You will get", toilet_roll / 0.2, "clubcard points for you...
import random import sys import time if __name__ == "__main__": if len(sys.argv) < 3: # no argumemnts, print usage message print("Usage:") print(" $ python3 similarity.py <data_file> <output_file> [user_thresh (default = 5)]") sys.exit() #Save arguments data_file = str(sys.argv[1]...
""" Problem: Find the sum of the only ordered set of six cyclic 4-digit numbers for which each polygonal type: triangle, square, pentagonal, hexagonal, heptagonal, and octagonal, is represented by a different number in the set. Nota bene: * Polygonal numbers are also called figurate numbers Performan...
from math import gcd def lcm(numbers): """ Computes the Least Common Multiple of a series of numbers Origin : Problem 5 """ least_multiple = 1 for number in numbers: least_multiple *= number // gcd(least_multiple, number) return least_multiple def prod(iterable, start=1): for...
""" Problem : Find the sum of the only eleven primes that are both truncatable from left to right and right to left. Nota bene : 2, 3, 5, and 7 are not considered truncatable, so remove them from the answer. Performance time: ~20s """ from primes import generate_primes from primes import is_prime f...
""" Problem : What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way? Performance time: ~0.0010s """ from timer import timer timer.start() answer = 1 for i in range(2, 1002, 2): for j in range(1, 5): answer += (i-1) ** 2 + j * i print(answer) timer.s...
# python function can return multiple values together. # other language like C,C++ or Java needs a class or structure for the same reason. def add_multiply(a, b): sum = a+b; product = a*b return sum, product m, n = add_multiply(10, 20) print("m: " +str(m) + " n: " + str(n))
def prompt(): print("Please enter an integer value: ") # Start of program print("This program adds together two integers.") prompt() # Call the function value1 = int(input("Testing to get input from console")) # all console input are string so, convert it into integer prompt() # Call the function again value2 = in...
## for, while loop, continue, break def main(): x = 2 while(x != 0): print x x -= 1 # --x or x-- are not supported print "##############" for x in range(2,5): # [2,5) print x for x in range(2,6,2): # [2,6) with interval 2 print x print "#############...
#!/usr/bin/env python # -*- coding: utf-8 -*- import math from labmet.labmetExceptions.labmetExceptions import InputTypeException class ThornthwaiteETo(object): """Thornthwaite ETo Empirical method based only on the mean air temperature, which is its main advantage. It was developed for wet weather...
import numpy as np def normalizeInput(inputImages, precalculatedMeans = None, precalculatedStds = None): """ Normalize input such that the mean is 0.0 and std is 1.0 for each channel Args: inputImages: an Numpy array that contains all the images. Assume the input is 3D or 4D array ...