text
stringlengths
37
1.41M
a = input("enter a number :") print(f"your number is , {a}") print("this is the movie") print(f" {}")
# -*- coding: utf-8 -*- #William Cooper #Data Mining #CU Boulder #Information code adapted from https://gist.github.com/iamaziz/02491e36490eb05a30f8 by Aziz Alto from __future__ import division from math import log import matplotlib.pyplot as plt import numpy as np import pandas as pd import csv #Normalizes data be...
#!/usr/bin/python3 #coding=utf-8 from tkinter import * import time import random DELAY = 20 TIMEMOD = 1 #modifier of time. FL1 = 1 #Flow 1 FL2 = 1 #Flow 2 - cars per second arived DISTANCE = 40 MINDISTANCE = 20 def onTimer(highWay, canvas): highWay.update(canvas, 20*TIMEMOD) #20 ms between updates of window i...
# Michell Valdivia # CS 480 Lab 3 # This file contains the UI for the calculator import tkinter as tk import simpleParser from functools import partial class Application(tk.Frame): # set up the main window def __init__(self, master=None): super().__init__(master) self.master = mas...
import numpy as np def sigmoid(x): # SİGMOİD FONKSİYONU TANIMLANDI return 1/(1+np.exp(-x)) def sigmoid_der(x): # SİGMODİDİN TÜREVİ TANIMLANDI return x*(1-x) class NN: def __init__(self,inputs): # yapıcı fonksiyon olması gerekli self.inputs=inputs ...
''' Created on Dec 3, 2010 @author: patricknevindwyer Gregorian breakdown of Time - any time breakdown dependent upon quantization of days, hours, and minutes. ''' from measurement.bases import Time from measurement.time.si import seconds minutes = Time( unit = 'minute', toBaseUnit = 60.0, fromBaseUnit =...
class BinarySearchTree(): class _Node: __slots__ = '_element', '_right', '_left' def __init__(self, element, left=None, right=None): self._element = element self._right = right self._left = left def __init__(self): self._root = None self._size...
""" ------------------------------------------------------- Area of a Cylinder To calculate the area of a cylinder ------------------------------------------------------- Author: Mason Cooper ID: 140328200 Email: coop8200@mylaurier.ca Version: 2014-09-19 ------------------------------------------------------- "...
""" ------------------------------------------------------- sum of squares continuing calculates the sum of squares until user prompts the program to stop ------------------------------------------------------- Author: Mason Cooper ID: 140328200 Email: coop8200@mylaurier.ca Version: 2014-09-19 ------------ """ ...
""" ------------------------------------------------------- [filename].py [description of main program] ------------------------------------------------------- Author: Mason Cooper ID: 140328200 Email: coop8200@mylaurier.ca Version: 2014-12-03 ------------------------------------------------------- """ MONTHS =...
""" ------------------------------------------------------- ------------------------------------------------------- Author: Mason Cooper ID: 140328200 Email: coop8200@mylaurier.ca Version: 2014-09-19 ------------ """ amountData = float(input("How much data will be transmitted(GB)? ")) fastestSpeed = float(inp...
import time import os import urllib.request import webbrowser X=''' Press 1: to check current date and time Press 2: to create a file Press 3: to create a directory Press 4: to search something on google Press 5: logout your system Press 6: reboot your OS Press 7: to check internet connection Press 8: to login what...
from collections import deque def rotateLeft(d, arr): items = deque(arr) while d > 0: item = items.popleft() items.append(item) d -= 1 return list(items) arr = [1,2,3,4,5] d = 2 print(rotateLeft(d,arr))
def caesarCipherEncryptor(string, key): # Write your code here. newLetters = [] newKey = key % 26 for letter in string: newLetters.append(getNewLetter(letter, newKey)) return "".join(newLetters) def getNewLetter(letter, key): newLetterCode = ord(letter) + key return chr(newLetterCod...
ratio = open('ratio.txt','r') print (ratio.read()) amount = 0 distance = float(input('Enter Distance : ')) amount += 35 if distance <= 1: amount = amount elif distance <= 5: distance -= 1 amount += distance*2 elif distance <= 10: distance -= 5 amount += 8 amount += distance*2.5 elif distance <=...
print "Inserisci a e b per svolgere un equazione di primo grado " a = input("Inserisci a : ") b = input("Inserisci b : ") if a==0 and b==0 : print " a e b sono uguali a 0 , quindi l'equazione ammette infinite soluzioni. " elif a == 0 : print " a e' uguale a 0 , quidi il risultato dell'equazione e' impossibi...
name = input("Enter file:") if len(name) < 1 : name = "mbox-short.txt" handle = open(name) l3 = dict() for l1 in handle: if l1.startswith("From") and not l1.startswith("From:"): l2=l1.split() # print("l2",l2[5]) #if l3 is None: l4 = l2[5].split(':') l3[l4[0]] = ...
################################################################################################ # Python authorisation # Write a program that asks the user for a username and password. (7 marks) # -> The program keeps asking for the username and password until the correct username and # password have been e...
# Jacobi Algorithm def get_value(arr, i, j): # if array out of bounds then return 0 if i < 0 or i > 9 or j < 0 or j > 9: return 0 else: return arr[i][j] def stencil(arr, i, j): # if on the unchangeable corners return 35 if (i == 9 and j == 9) or (i == 0 and j == 0): return ...
''' The Rules of the rock-paper-scissors are: Rock > Scissors , Paper > Rock , Scissors >Paper If both choice the same (Rock=Rock,Paper=Paper Scissors=Scissors) the result is a tie . ''' #using if/elif statements import random user=input("What's your choice ? 'r' for rock,'p' for papper and 's' for scissors:...
def hanoi (n,p_inicial,p_final,p_auxiliar): if n == 1: print("Pasa el disco de la posicion: " + p_inicial+","+" a la posicion: "+p_final) else: hanoi(n-1,p_inicial,p_auxiliar,p_final) print("Pasa del disco de la posicion: "+p_inicial+","+" a la posicion: "+p_final) hanoi(n-1,p_au...
def postorden(pre, ino): #Se revisa si la cadena esta vacia, para retornar la cadena de postorder vacia if pre == "": return "" #Si la cadena tiene un caracter, por lo tanto el post order va a ser ese mismo caracter if len(pre)==1: return pre PostOrden = "" Ino_izq = "" Pre_i...
import math #Libreria que permite la raíz cuadrada status = input("\n1.- Falta la hipotenusa \n2.- Falta el cateto grande \n3.- Falta el cateto pequeño \n") #a == Hipotenusa #b == Cateto grande #c == Cateto pequeño def hipotenusa(): b = int(input("Introduce el tamaño del cateto más grande: ")) ...
from model import Artist from model import Artwork def display_menu_get_choice(menu): while True: choice = input('Enter choice? ') if menu.is_valid(choice): return choice else: print('Not a valid choice, try again.') def message(msg): print(msg) def show_artwo...
""" Author: Clint Kline Date Created: 5/26/2021 Last Modified: 06/01/2021 Purpose: Renames JPG, PNG, and GIF image files by type in a folder in numeric order beginning with 01. ------------------------------------------------- Instructions: - Paste file in desired folder. - Open file in your favorite cod...
import pygame from libs.OsObj import OsObj class Queue(OsObj): def __init__(self): super().__init__(pygame.Rect((300, 40), (420, 60)), \ pygame.font.SysFont(None, 30), (255, 0, 0)) self.queue = [] self.cellWidth = 60 self.max_len = 7 def draw(self, window): ...
# The prime 41, can be written as the sum of six consecutive primes: # 41 = 2 + 3 + 5 + 7 + 11 + 13 # This is the longest sum of consecutive primes that adds to a prime below one-hundred. # The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953. # Which...
#Each new term in the Fibonacci sequence is generated by adding the previous two terms. #starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 #By considering the terms in the Fibonacci sequence whose values do not exceed four million #find the sum of the even-valued terms. def fibonacc...
# The sum of the squares of the first ten natural numbers is, # 12+22+...+102=385 # The square of the sum of the first ten natural numbers is, # (1+2+...+10)2=552=3025 # Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025−385=2640. # Find the difference...
# -*- coding: utf-8 -*- """ Created on Thu Dec 21 10:29:42 2017 @author: abyss """ def valid_yesno(entry): yes = {'yes','y', 'ye'} no = {'no','n',''} if entry in yes: return True elif entry in no: return False else : print ("Layer 8 issue, skipping") return Fal...
#!/usr/bin/python3.6 print('What is 2 + 2?') answer = input() if answer == '4': print('That is correct!') else: print('That is not correct')
# find area and perimeter of a polygon from math import * def polysum(n, s): ''' n, s: positive integers returns: positive integer, sum rounded to 4 decimal places ''' area = 0.25*n*s**2/tan(pi/n) perimeter = s * n result = area + perimeter**2 print(round(result,4)) polysum(75, 53)
import nltk from nltk.stem import WordNetLemmatizer filetext=open('input.txt','r',encoding='utf-8') text=filetext.read() #creating instances of tokens wordtokens=nltk.word_tokenize(text)#word tokens lemma=WordNetLemmatizer()#creating an instance of lemmatizer for w in wordtokens: print(w) print(lemma.lemmatize(...
import unittest class MyTest(unittest.TestCase): # 继承unittest.TestCase def setUp(self): print('Call setUp') def tearDown(self): # 每个测试用例执行之后做操作 print('Call tearDown') @classmethod def setUpClass(self): # 必须使用@classmethod 装饰器,所有test运行前运行一次 print('Call setUpClass') ...
import random """ A general guide for hangman 1. Make a word bank - 10 items 2. Pick an random item from the list 3. add a guess to the list of letters guess 4. Reveal letters already guessed 5. Create the win condition """ guesses_left = 10 if output == list(random_word): print("Congrats You Win word_ba...
# -*- coding: utf-8 -*- """ Created on Sat Jan 16 19:30:42 2021 @author: asarkar """ import random import matplotlib.pyplot as plt def display_image(dataset): # Adjust the size of your images plt.figure(figsize=(20,10)) for i in range(9): num = random.randint(0,len(dataset)-1) plt.subplot(3,...
from .habitat import ContainsAnimals from .habitat import ContainsPlants class Biome: def __init__(self, name, max_animals, max_plants): self.name = name self.max_animals = max_animals self.max_plants = max_plants def exceed_max(self, what_organism): try: if what_...
import pygame from pygame.sprite import Sprite class Ship(Sprite): def __init__(self,ai_game): ##self argument and AlienInvasion class instance argument super().__init__() self.screen=ai_game.screen ##assigns screen(AlienInvasion class screen) to the attribute of the ship self.settings=ai_game.settings ##c...
from math import * #사용자가 각 도형의 길이를 입력하도록 r=input("원의 반지름의 길이 :") a=input("정삼각형 한 변의 길이: ") #입력된 변수를 정수로 바꾼다. r=int(r) a=int(a) #내장 함수와 입력된 변수를 이용한 계산 출력 print("원의 둘레=", 2*pi*r) print("원의 넓이=", pi*r**2) print("정삼각형의 둘레=", a*3) print("정삼각형의 넓이=", sqrt(3)/4*a**2) #루트3 - 내장 함수 sqrt호출 sqrt(3) #원주율 ...
#List 선언 A=[1, 3, 5, 7, 8, 9] print("초기 List:", A, "\n") #List 요소 추가, 삽입 A.append(4) print("append(4)의 결과:", A, "\n") A.insert(1, 2) print("insert(1, 2) 결과:", A, "\n") #List 확장 A.extend([5, 6]) print("extend[5, 6]의 결과:", A, "\n") #List 요소 제거 A.remove(5) print("remover(5) 결과:", A, "\n") del A[3:5] p...
#a,b의 값을 사용자가 입력할 수 있도록 함 a=input("a를 입력하세요. a=") b=input("b를 입력하세요. b=") #a, b를 정수로 설정 a=int(a) b=int(b) #정수로 바꾼 a, b 계산 및 출력 print("a+b=", a+b) print("a-b=", a-b) print("a*b=", a*b) print("a/b=", a/b)
class Employee: company = "Beehyv" #salary = input("Enter your salary: ") #bonus = input("Enter your bonus: ") @staticmethod def getSalary(salary, bonus): totalSalary = salary + bonus return totalSalary abhijit = Employee() sal = abhijit.getSalary(600000,30000) print(f"Your total...
import math def detect_triangle(a, b, c): ep = pow(10,-9) if((a < 0)|(b < 0)|(c < 0)|(a > (pow(2,31)-1))|(b > (pow(2,31)-1))|(c > (pow(2,31)-1))): return "Vuot qua mien gia tri" else: if((a+b>c)&(b+c>a)&(a+c>b)): if((a == b)&(b == c)): return "Tam giac deu" ...
a = [1] b = [0] n = int(input("Enter the size: ")) for i in range(n): print(a) a = [j+k for j,k in zip(a+b, b+a)]
count = ['1','2','3','4','5'] fruits = ['apples','oranges','graps','mangos'] change = [1,'pennies','2','dimes','3','quarters'] #this first kind of for goes through a list for no in count: print "this is count %s" % no for fruit in fruits: print "A fruit of type %s" %fruit for g in change: print "I got %r" %g #...
people = 30 cars = 30 buses = 30 if cars > people: print "we should take cars" elif cars < people: print "we should take people" else: print "we can't decide." if buses > cars: print "That's too many buses" elif buses < cars: print "That's too many cars" else: print "We cant decide" if people > buses: print "...
from sys import argv script,filename = argv print "We're going to erase %r" %filename print "If you don't want hit CTRL-C (^c)." print "If you do want then, hit RETURN" raw_input(">") print "Opening file.." target = open(filename,"w") print "Truncating the file..Goodbye!" target.truncate() print "Now I'm gonna ask y...
# Ronni Sole tæller = 1 total = 0 u = 230 print('Efter indtastning bekræft med Enter!') while tæller: tæller += 1 total += int(input("Hvor mange watt er apparatet på? : ")) fort = input('Vil du indtaste en enhed mere? ') if 'ja'.startswith(fort.lower()): print('Vi fortsætter') else: ...
#!/usr/bin/env python # coding: utf-8 # # Machine Learning using Regularized Logistic Regression # # Classifier model that predict whether microchips from a fabrication plant passes quality assurance (QA). # In[1]: import pandas as pd import numpy as np # import pandas_profiling import seaborn as sns import matplo...
from card import Card class Deck: """ Deck Class - creates and instance of a 52 card French deck There is no need to access the function directly, unless a user wants to customize the Deck Class. Users can specify the number of decks through the CustomizeDeck Class. """ id = 0 ...
# -*- coding: utf-8 -*- """ Created on Fri Jun 25 08:51:21 2021 @author: Relic """ ##Print Multiplation Table ###Goal 1: Print 1 Row #for columnIndex in range(1,10): # print(1*columnIndex,end=' ') # # ##Goal 2: Print 2 Row #for columnIndex in range(1,10): # print(2*columnIndex,end=' ') ...
# strings stored in variables first_name = 'Asa' print(first_name) # no keyword required to set a variable just give it a name # combine strings with + operator last_name = 'Shalom' print('Greetings ' + first_name + ' ' + last_name) # variable naming convention in python is always lower # case if more than one word...
import copy import random import time import math class Queue(): def __init__(self): self.queue = [] def isEmpty(self): if len(self.queue) == 0: return True return False def get(self): if not self.isEmpty(): first = self.queue.pop(0) return first return False def add(self, value): if isinst...
from sys import argv, exit import csv if len(argv) != 3: print("usage: python dna.py [cvs file] [file.txt]") exit(1) # STRs array strs = [] # open database and sequence database = open(argv[1], "r") sequence = open(argv[2], "r") # read database dbReader = csv.reader(database) # read sequences file sequences...
# Todos: # make object oriented # change order to display # Search feature # Old options: print("Enter: 1 to add, 2 to remove, 3 to move") # "4 to search, 5 to create a new list, 6 to see existing lists") import os class TodoList: def __init__(self): self.todos = ['todos', 'here'] s...
#快速找到索引 test = [10,3,5] for i,value in enumerate[test]: print(i,':',value)
#daily challenge 12-12-2013 #hardware pricing #my goal for this is to create two lists order them compare and output the discrepcy PRICELIST = 'prices.txt' if __name__ == '__main__': #saves the items from the file into a list to work with list = open(PRICELIST).readlines() #pop the number off the list so we can s...
def swapchars(instring): lettercount = [0] * 26 # Count the occurance of each character for c in instring: if (c.isalpha()): lettercount[ord(c.upper()) - ord('A')] += 1 # Find the most and least common most = 0 least = len(instring) most_index = 0 least_index = 0 ...
import random # n = raw_input("How large should your square grid be? Choose a number between 1 and 10.") # n = int(n) n=7 def create_mine_grid(n): mine_list = [] while len(mine_list)<n: mine_list.append([]) for i in range(n): while len(mine_list[i])<=n: mine_list[i].append('x') return mine_list mine_g...
''' See the problem description https://adventofcode.com/2020/day/2 ''' def error_one() -> int: ''' Return the number of acceptable passwords ''' count = 0 f = open("input.txt", "r") for val in f: condition, password = val.split(':') amounts, letter = condition.split(' ') ...
# Name: Ben Koczwara # Date: Sept.13,2013 # Purpose: to create a program that will create a simple mad lib import random print "Mad Lib" print "-------" print print "This program will generate a random phrase with a plural noun, verb and singular noun" print again = "y" while again == "y": verbs = ["run","sleep",...
# Name: Ben Koczwara # Date: Sept.26,2013 # Purpose: create a program that will find the number of variables, average, highest and lowest value filename = "Values.txt" info = open(filename,"r") print "Information about 'Values.txt'" print "------------------------------" print print "This program will tell you the nu...
# Name: Ben Koczwara # Date: Sept.13,2013 # Purpose: to create a program that will make a list of 1000 values and find the number entered import random print "Random Numbers" print "--------------" print print "This program will create a list of 1000 integers from 1 to 100. When" print "you enter a number between 1 an...
# Name: Ben Koczwara # Date: Oct.15,2103 # Purpose: to create a program that returns the lowest prime factor of a number def Factor(number): x = 2 while x != number: if number%x == 0: y = 2 while x != y : if x%y == 0 and y != 2: ...
# Name: Ben Koczwara # Date: Oct.22,2013 # Purpose: create a program that will print out some golf game results print "Golf Game Application" print "---------------------" print grid = [[0 for x in range(0,9)] for w in range (0,4)] players = [] for x in range(1,5): name = raw_input("Enter the name of player "+s...
# Name: Ben Koczwara # Date: Oct.16,2103 # Purpose: to create a program that will determine a fractions lowest possible form' from fractions import Fraction def GCD(n,d): if n > d: num = n/d n -= (num*d) fraction = Fraction(n,d) else: num = 0 frac...
import requests import json def COVID_API(): URL = 'https://localcoviddata.com/covid19/v1/cases/covidTracking' parameters = {'state' : input("Which state do you want COVID-19 data for? \n(Enter the state's capitalized two letter code) "), 'daysInPast': 1} response = requests.get(URL, params= paramete...
segundos_str=input("Número de segundos a converter:") total_segs=int(segundos_str) horas=total_segs // 3600 segs_restantes=total_segs %3600 minutos=segs_restantes//60 segs_restantes_final=segs_restantes%60 print(horas,"horas",minutos,"minutos e", segs_restantes_final,"segundos.")
num=int(input("Digite um número inteiro:")) s=0 while(num>0): r=num%10 num=num//10 s=s+r print(s)
x=int(input("Digite um número inteiro:")) unidade=x%10 x=(x-unidade)//10 dezena=x%10 print("O dígito das dezenas é",dezena)
# Lesson 34 - - - - - - - - - - - - - - - - - - - - - - - - - import pandas as pd import os os.chdir('D:/python_lesson/Scripts') d1 = pd.read_csv('k1.txt', header=None, sep=',') ## output first four rows and first three columns print(d1.iloc[0:4, 0:3]) ## how many columns print(len(d1.columns)) ## how many rows...
with open('input', 'r') as file: lines = [line.strip() for line in file if line.strip()] ranges = {} part = 1 error_rate = 0 ticket = [] valid_tickets = [] cols = 0 for line in lines: if "your ticket" in line: part = 2 continue if "nearby tickets" in line: part = 3 ...
#获得数据 def getNum(): nums = [] iNumStr = input("请输入数字(按回车换行结束):") while iNumStr != "": nums.append(eval(iNumStr)) iNumStr = input("请输入数字(按回车换行结束):") return nums #计算平均值 def mean(numbers): s = 0.0 for num in numbers: s = s + num return s / len(numbers) ...
while[1 == 1]: MONEY = input("请输入一种金钱数:") if MONEY[0] in ['$']: if MONEY[1] in ['1','2','3','4','5','6','7','8','9']: RMB = eval(MONEY[1:])*6 print("转换过后的钱是RMB:{:.2F}".format(RMB)) else: print("ERROR") elif MONEY[0] in ['R','R']: if MONEY[...
def multi(a): if a >= 10: x = a%10 return x*multi((int)(a/10)) else: return a def main(): num = eval(input("请输入一段参数:")) al = multi(num) print("各项参数的乘积为:{}".format(al)) main()
from random import randint x=0 a = randint(0,9) while True: try: i = int(input("请输入一个整数:")) except: print("错误!请输入一个整数!") #break else: x += 1 print("这是用户第{}次正确输入".format(x)) if i == a: print("预测{}次,你猜中了!".format(x)) break ...
import random def Same(): dic= {} c = 0 count = 0 counts = 0 time = pow(2,15) people = 23 for cx in range(time): while c <= time: for i in range(people): dic[i] = random.randint(1,366) if isSame1(dic,people): coun...
class Solution: def distributeCandies(self, candies): """ :type candies: List[int] :rtype: int """ # return int(len(candies)/2 if len(set(candies)) > len(candies)/2 else len(set(candies))) return int(min(len(candies)/2, len(set(candies))))
# class Solution: # def hasAlternatingBits(self, n): # """ # :type n: int # :rtype: bool # """ # def is1010(n): # if n == 0: # return True # elif not n%2: # return is10101(n>>1) # else: # retu...
class Solution: def addDigits(self, num): """ :type num: int :rtype: int """ # 关键在于Go中 -1%9 = -1 而python3中 -1%9 = -8 return (num-1)%9 + 1 if num > 0 else 0 # 64ms, 其他的方法没什么意思
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ # if not head or not head.next: # 44ms # ...
class Solution: def fizzBuzz(self, n): """ :type n: int :rtype: List[str] """ # ans = [] # for num in range(1, n+1): # if not num%3 and not num%5: # ans.append("FizzBuzz") # elif not num%3: # ans.append("Fizz") #...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def convertBST(self, root): """ :type root: TreeNode :rtype: TreeNode """ # def recursion(node, v...
class Solution: def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ ans = [] def recursion(s='', left=0, right=0): if len(s) == 2*n: ans.append(s) if left < n: recursion(s+'(', left+1, right)...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ # def reverse(node): # ...
# -*- coding: utf-8 -*- from operator import add, mul, truediv, sub, neg, floordiv from math import sin, pi, e try: import readline except ImportError: pass FUNCTIONS = { 'sin': (1, sin), '+': (2, add), '*': (2, mul), '/': (2, truediv), '//': (2, floordiv), '-': (2, sub), 'neg': (1...
""" Example tests using standard documentation. https://docs.python.org/3/library/unittest.html """ import unittest from oop_examples import Bicycle class TestBicycle(unittest.TestCase): """tests the usage of Bicycle""" def setUp(self): self.bike1 = Bicycle('giant', 'L', 32, 'roady') self.b...
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) # create a placeholder tensor of dimension x X 784, x is of arbitrary length x = tf.placeholder(tf.float32, [None, 784]) # weights W = tf.Variable(tf.zeros([784, 10])) # b...
''' Created on Nov 12, 2015 @author: Mika ''' import random import sys import UpdateList import DrawHangman def CallHangmanGame(Press): if Press=='1': #Generate random number RandomIndexWord= random.uniform(0, 10) RandomIndexWord=int(RandomIndexWord) #Read specific line from f...
# -*- coding: utf-8 -*- """ Created on Thu Apr 16 23:22:48 2020 @author: Shekhar.Maurya Code Challenge Name: Target Heart Rate Calculator Filename: heartrate_cal.py Problem Statement: Calculate the Maximum Heart Rate and Target Heart Rate Range ( Lower and Higher value ) of a per...
# -*- coding: utf-8 -*- ''' This module demonstrates how non-linear control algorithm works for two-arm manipulator Example ------- $ python main.py -a -c="passivity adaptive" -m="tracking sine function" Notes ------- there are 3 command line option -a, --animation: default False, if True, en...
#Memasukkan Dua Bilangan Bulat x = int(input("Masukkan bilangan bulat :")) y = int(input("Masukkan bilangan bulat :")) #Operator Floor hasil = x // y #Menampilkan Hasil print("hasil bagi :", hasil)
# возрастной коэффициент, который влияет на платёжеспособность12 # возраст, размер кредита и количество месяцев age_coeff = 0 credit_time = int(input("На какое время вы берете кредит:"+" ")) # Вреия, на которое берется кредит credit_size= int(input("Укажите размер кредита:"+" ")) # размер кредита percent = int(input(...
def permutations(input_list): if len(input_list) == 0: return [[]] else: moving_element = input_list[0] mega_arr = [] permutated_list = permutations(input_list[1:]) for list_index in range(len(permutated_list)): for list_element_index in range(len(perm...
# считаем общее кол-во рулонов def calculate_rolls_count(roll_l, roll_w, room_l, room_w, ceiling_h): """ >>> calculate_rolls_count(10, 1.06, 10, 10, 2.75) 13.0 """ room_perimeter = calculate_perimeter(room_l, room_w) canvas_count = calculate_canvas_count(room_perimeter, roll_w) canvas_in_rol...
from random import random from cell import Cell from time import sleep class Grid(): def __init__(self, sizex, sizey): self.sizex = sizex self.sizey = sizey self.cells = [] self.grid = [] def randomCell(self): for i in range(self.sizey): for j in range(self....
def non_reapeating_char(): string = input("Enter the string:") num = len(string) for i in range(0, num + 1): if i == 0: if string[i] != string[i + 1]: print(string[i]) # break elif i == num + 1: if string[i] != string[i - 1]: ...
class Circle: def __init__(self,radius): self.radius=radius def find_area(self): return 3.14*self.radius**2 def find_perimeter(self): return 2*3.14*self.radius radius=int(input("Enter the radius:")) r=Circle(radius) print("Area of circle:",r.find_area()) print("Perimeter of circle:"...
number = int(input("enter the elements in list:")) array_1 = list() print("enter number in array:") for i in range(0, int(number)): n = int(input("enter num:")) array_1.append(int(n)) print("List is:", array_1) array_1.sort() print("sorted list is:", array_1) for i in range(len(array_1) - 1): if array_1...
my_dict = {} def find_pass_result(): num = int(input("Enter the persons")) for i in range(0, num): id = int(input("Enter the id")) result = str(input("Enter the result")) name = str(input("Enter the name")) print({"id: {} result: {} name: {}".format(id, result, name)}) ...