text
stringlengths
37
1.41M
import math def primechecker(number): t = False for i in range(2,number): if number%i==0: t = True break if t==True: print(str(number)+" is not a prime") else: print(str(number)+" is a prime") n = int(input()) final = False for i in range(2,n): ...
principal = float(input("Enter Principal P > ")) rate = int(input("Enter the rate R > ")) time = int(input("Enter the time T > ")) simple_interest = (principal * rate * time) / 100 print("The Simple Interest is {}".format(simple_interest))
#!/usr/bin/python # # オブジェクトとクラス # # class によるクラスの定義 class Nothing(): # 空のクラス pass someone = Nothing() # NothingPerson インスタンスの生成 class NothingToInit(): # コンストラクタをもつクラス def __init__(self): # コンストラクタ pass class Person(): def __init__(self, name): ...
import random chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' l=int(input("Enter password length: ")) n=int(input("Enter number of passwords: ")) for i in range(n): password='' for j in range(l): password+=random.choice(chars) print(password)
# 集合(set)是一个无序的不重复元素序列。 # 可以使用大括号 { } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。 # 然后 是集合之间的一些运算 # 交叉并补 # 1. 集合的基本操作 s={1,1,2,3,4,2} print(s) s.add(5) print(s) s.remove(5) print(s) s.pop() print(s) print(len(s))
# 1. 列表切片 # 2. 更新列表 # list=['Google', 'Runoob', 1997, 2000] # 2.1 更改列表某个元素 # print(list) # list[0]="baidu" # print(list) # 2.2 往列表中增加元素 # list.append("sougou") # print(list) # 2.3 删除列表中某个元素 # print(list) # del list[2] # print(list) # 3. 列表同时也支持 拼接,重复,截取 # 4. 也可嵌套 # list=[['a', 'b', 'c'], [1, 2, 3]] # print(list[0...
age=int(input("请输入你家狗狗的年龄:")) # 这里 if age<=0: print("erro!") elif age==1: print("相当于 14 岁的人。") elif age==2: print("相当于 22 岁的人。") elif age>2: human=22+(age-2)*5 print("对应人类年龄: ",human) # 判断 input 默认设置的数据类型 inp=input("输入一个数,判断 input 默认设置的数据类型:") print(type(inp)) # 默认是 字符串
import os from math import factorial from itertools import permutations def borrarPantalla(): #Definimos la función estableciendo el nombre que queramos if os.name == "posix": os.system ("clear") elif os.name == "ce" or os.name == "nt" or os.name == "dos": os.system ("cls") def getFileName()...
#coding UTF-8 #Тренировочная программа-игра для отработки навыков написания кода Python import random import sys print('Здравствуйте! Пожалуйста, отгадайте число, загаданное мной.') print('') def game_main(): a = random.randint(1, 100) def int_check(): x = int(input('Какое число я загадал? ')) ...
def init(newWord): letterIn = input("Type your guess (1 letter or character): ") #ask for a letter and capture input #loop through string to see if letter is in string word = newWord["newWord"] length = newWord["numOfChar"] error = 0 for i in word: if letterIn == word[i]: in...
# 1. Map = fungsi map berlaku ke semua items dalam sebuah input_list # sintaks = map(function_to_apply, list_input) # contoh : # biasanya kita ingin pass semua list elemen ke sebuah fungsi satu-demi-satu dan mengambil output item = [1,2,3,4,5] square = [] for i in item: square.append(i**2) print square print '\n...
def add_to(num, target=[]): #ingat list harus dibelakang target.append(num) return target add_to(1) def add_to2(element, target2=None): if target2 is None: target2 = [] target2.append(element) return target2 add_to2(3)
#汉诺塔移动 #汉诺塔游戏的规则是三根柱子,其中一个柱子上有从下往上从大到小的N个罗盘,每次移动1个罗盘,其中大罗盘不能放在小罗盘之上,最后把罗盘从A柱移动B柱。 #分别用递归函数或者循环的方式去实现 #使用递归函数去解决,递归函数就是要找到逻辑关系 #1.假设有A,B,C三根柱子,罗盘初始在A柱上,最后有移动到C柱。我们首先要想办法把最下面最大的罗盘移动到C柱上,这个时候B柱上有N-1个罗盘,A柱上没有罗盘,C柱上有一个最大的罗盘。 #2.这个问题此刻又变成了将B柱上的N-1个罗盘移动到C柱,这本身就形成了一种递归。 #综合上面的分解,把汉诺塔拆解成散步,第一步将n-1个盘子移动到B柱上,第二步将A柱上的罗盘移动到C柱上,第三部...
#----------------------------------------------------------------------------- # Name: Word Guessing Game.py # Purpose: Make a hangman type game # # Author: Daniel # Created: 07-Oct-2020 # Updated: 14-Oct-2020 #----------------------------------------------------------------------------- # I thi...
# -*- coding: utf-8 -*- """ Created on Sat Jan 18 17:00:12 2020 @author: rober """ from enum import Enum class Type(Enum): INT = 'INT' STR = 'STR' BOOL = 'BOOL' class Null(Enum): NULL = 'NULL' class Node: def __init__(self, node_func, value=None, input_nodes=None, is_input=False, is_output=Fals...
from math import ceil, floor, sqrt def simpRootFrac(num, root, intd): # takes in a numerator, and the two parts of the irrational root # simplify by mutliplying by the conjugate # returns whole number, plus 3 parts of remaining fraction. newIntNum = -intd newDenom = root - intd * intd newD...
def is_sum_of_pows(num, pow): total = 0 s_num = str(num) for d in s_num: total += int(d) ** pow return total == num fith_nums = [] for n in range(10, 1000000): if is_sum_of_pows(n, 5): fith_nums.append(n) print(sum(fith_nums))
from math import sqrt def is_pent(n): N = (1 + sqrt(24 * n + 1)) / 6 return N % 1 == 0 def is_tri(n): N = (sqrt(8 * n + 1) - 1) / 2 return N % 1 == 0 h = 144 while True: H = h * (2 * h - 1) if is_tri(H) and is_pent(H): print(H) break h += 1
from functools import cache from sympy import primerange @cache def count_decreasing_prime_sums(n, max=None): if n == 1: return 0 if n == 2: return 1 max = max or n total = 0 for first_addend in primerange(2, min(max + 1, n)): total += count_decreasing_prime_sums(n - first_...
'''Преобразовать IP-адрес (переменная IP) в двоичный формат и вывести вывод столбцами на стандартный поток вывода, таким образом: первой строкой должны идти десятичные значения байтов второй строкой двоичные значения Вывод должен быть упорядочен также, как в примере: столбцами ширина столбца 10 симво...
from sys import argv import re filename, regex = argv[1:] def regex_func(filename, reg_ex): with open(filename, 'r') as text: ip_list = [] for line in text: match = re.search(reg_ex, line) if match: ip_list.append(match.group()) return ip_list print(reg...
'''6.1a Сделать копию скрипта задания 6.1. Дополнить скрипт: Добавить проверку введенного IP-адреса. Адрес считается корректно заданным, если он: состоит из 4 чисел разделенных точкой, каждое число в диапазоне от 0 до 255. Если адрес задан неправильно, выводить сообщение: 'Incorrect IPv4 add...
class BinaryTreeNode(): """represents a node of the tree. Leaf nodes are represented by None. You can add to this class.""" def __init__(self, key, value, left=None, right=None): self._key = key self._values = [value] self._left = left self._right = right def inser...
import turtle as t import random color=["red","white","black","pink","greenyellow"] size=50 def draw_dot(x,y): t.up() t.goto(x,y) t.dot(size) def draw_triangle(x,y): t.up() t.goto(x,y) t.down() t.begin_fill() for i in range(3): t.forward(size) t.left(36...
# -*- coding: utf8 -*- ''' This module takes a collection as input, and builds a "reversed index": word -> items There are then 3 ways to search: exact=True -> finds all items containing the exact term exact=False -> finds all items containing the prefix (slower) TODO!!! onlyin=[keys] -> returns only the...
#Advanced Loops def function(rows,columns): for row in range(6): #0,1,2,3,4 if row % 2 != 0: #0 for column in range(1,6): if column % 2 == 1: if column != 5: print("",end = "") else: print(" ...
# Animals - Part A, B class Pet: def __init__(self,n,a,h,p): self.name = n self.age = a self.hunger = h self.playful = p #getters def getName(self): return self.name def getAge(self): return self.age def getHunger(self): return self.hunger ...
#Class 7 #breaking n continuing in loops #Participants = ["Alvaro","Sebastian","Johnny","Esmeralda","Dayanna"] # Position = 1 # for name in Participants: # if name == "Esmeralda": # break # Position += 1 # print(name) # print(Position) # #other-------------------------------------------- # for curren...
# Part A # from random import randint # randVal = randint(1,100) # while(True): # while(True==True): # guess = int(input("Input a number: ")) # if guess == randVal: # print("Ganaste") # break # elif guess < randVal: # print("Tu numero debe ser mas alto") # else: # pri...
class Employee: def __init__ (self,name, surname): self.name = name self.surname = surname self.position = type(self).__name__ def print_init(self): print(self.name, self.surname, self.position) class Programmer(Employee): pass class Manager(Employee): "this is de...
#Programa que convierte dolares a pesos. class Convertor(): def __init__(self, dolares): #definicion de propiedades de clase. self.dolares = dolares self.costoDolar = 3600 def ConvertirPesos(self): resultado = self.dolares * self.costoDolar return resultado ...
from pet import Pet class Program: def __init__(this): this.vacOptions = ("Vacunas: ", "1.Antirrabica", "2.Antipulgas", "3.Purgatoria") this.response = "" this.__afirmativeResponses = ["s", "si", "sii", "yes", "claro", "por supuesto", "obviamente", "siza", "siza pai"] this.option = ...
class Pay: def __init__(self): self.rango = "" self.horas = 0 trabajador = { "horas": 0, "rangos": ['bajo', 'medio', 'alto'] } def main(self): while True: try: horas = int(input("¿Cuántas horas trabajó?: ")) self.horas ...
from src.Carrito import Carrito class Program: def __init__(self): self.mensaje = "no" self.respuestas = ["s", "si", "sii", "yes", "claro", "por supuesto", "asi es", "siza pai"] self.opcionesRespuesta = { "primera": ["primera", "la uno", "la primera", "1"], "seg...
class Persona: def __init__(self, nombre): self.__nombre = nombre def __add__(self, este): return f"{self.__nombre} {este.__nombre}" p1 = Persona(5) p2 = Persona(5) p3 = Persona(5) print(p1 + p2)
def misDatos(): preguntas = ["Nombre", "Apellido", "Edad", "Tarjeta de Identidad"] respuestas = ["Brian", "Castro", "16", "1098306124"] for pregunta, respuesta in zip(preguntas, respuestas): print(f"¿Cual es tu {pregunta}? La respuesta es: {respuesta}") misDatos()
class Recarga: def __init__(self, cantidadMins: int): self.cantidadMins = cantidadMins self.valorMins = 100 self.__adicion = self.cantidadMins * 2 def Main(self): print(self.__str__()) def __HacerRecarga(self): recarga = self.cantidadMins * self.valorMins ...
import math class Triangle(): def __init__(this): this.side = { "a": 0, "b": 0 } this.__hypotenuse = 0 def hypotenuse(this, a, b): this.side["a"] = a this.side["b"] = b this.__hypotenuse = this.side["a"]**2 + this.side["b"]**2 thi...
class Sumatoria: def __init__(self, num1, num2): self.num1 = num1 self.num2 = num2 def sumar(self): return self.num1 + self.num2 suma = Sumatoria(float(input("Numero 1: ")), float(input("Numero 2: "))) print(f"El resultado de la suma de Num1 + Num2 es: {suma.sumar()}")
from tkinter import * from tkinter.messagebox import * import sqlite3 def login_user(username,password): con=sqlite3.connect("createuser.db") cur=con.cursor() cur.execute("select * from user") row=cur.fetchall() for i in row: if(i[0]==username and i[3]==password): s...
""" My Relational Operators Program """ __author__ = "730250025" left_hand_side: str = input("Left-hand side ") right_hand_side: str = input("Right-hand side ") first_number: int = int(left_hand_side) second_number: int = int(right_hand_side) less_than_number: int = int(first_number < second_number) bool_less_than_nu...
#!/usr/bin/python3 import os ROOT = input("What is the directory to be scanned? ") filesToRead = os.listdir(ROOT) writAble = [] for i in range(len(filesToRead)): print(filesToRead[i]) if filesToRead[i][0] == 't' and filesToRead[i][0] != '_': with open (ROOT + "/" + filesToRead[i], 'r', encoding='utf-8...
#elif= arias condiciones #ejemplo convertidor de numeros a letras de 1 a 5 print( "convertidor de numeros a letras") num= int(input("agrega un valor ")) if num==1: print("es el numero uno ") elif num==2: print("el numero es dos") elif num ==3: print("es el tres") elif num==4: print("es el cuatro") el...
#operadores relacionales print("comparacion de dos numeros") num1= int(input("ingrese numero 1 :")) num2=int(input("ingrese numero 2 :")) print("numeros a comparar " , str(num1) + "y" , str(num2)) if num1<num2: print("el" , str(num1) , "es menos que" , str(num2)) if num1>num2: print("el", str(num1), "es mayor ...
def add(a, b): """Function to add two numbers.""" c = a+b return f'Sum = {c}.' def fibonacci(n): # return Fibonacci series up to n result = [] a, b = 0, 1 while a < n: result.append(a) a, b = b, a+b return result
# -*- coding: utf-8 -*- """The attribute container interface.""" class AttributeContainer(object): """Class that defines the attribute container interface. This is the the base class for those object that exists primarily as a container of attributes with basic accessors and mutators. The CONTAINER_TYPE cla...
def expansion(current_path, successors): new = [] successors_names = [i[0] for i in successors] current_path_names = [i[0] for i in current_path] # print('successors:', successors) # search if in successors we have a node that has # already been visited on the current_path, so we # search ...
# start: node name # end: node name # conn: all the connections import elements.Connections as Connections import elements.Nodes as Nodes from algorithms.get_node_heuristic import get_node_heuristic def expansion_heuristic(current_path, successors, nodes: Nodes): new = [] successors_names = [i[0] for i in suc...
al = 0 gas = 0 di = 0 while (True): n = int(input()) if (n == 1): al+=1 if (n == 2): gas+=1 if (n == 3): di+=1 if (n == 4): break print('MUITO OBRIGADO') print(f'Alcool: {al}\nGasolina: {gas}\nDiesel: {di}')
import math a, b, c = input().split() a = float(a) b = float(b) c = float(c) delta = (b*b) - (4 * (a) * (c)) if (delta <= 0): print('Impossivel calcular') else: x1 = -b + math.sqrt(delta) x2 = -b - math.sqrt(delta) if ((x1 == 0) or (x2 == 0)): print('Impossivel calcular') else: x1 = x1 / (2*a) ...
cod1, num1, val1 = input().split() cod2, num2, val2 = input().split() cod1 = int(cod1) cod2 = int(cod2) num1 = int(num1) num2 = int(num2) val1 = float(val1) val2 = float(val2) val = (int(num1) * float(val1)) + (int(num2) * float(val2)) print('VALOR A PAGAR: R$ %0.2f'%val)
import constants as c from pprint import pprint from card import Card from player import BridgePlayer class BridgeHuman(BridgePlayer): ''' A human bridge player class which inherits from Player. ''' def __init__(self, dealt, num, name=None): ''' dealt: a Deck of cards dealt to this player ...
from art import logo # Calculator def add(a, b): return a + b def multiply(a, b): return a * b def subtract(a, b): return a - b def divide(a, b): if b == 0: return "invalid input" return a / b operations = { # key: symbol, value: method "+": add, "-": subtract, "*": mult...
# Code Exercise: Write a program that adds the digits in a 2 digit number. e.g. if the input was 35, then the output should be 3 + 5 = 8 two_digit_number = input("Type a two digit number: ") #################################### #Write your code below this line 👇 sum = 0; for d in two_digit_number: sum += int(d) p...
##################### Extra Hard Starting Project ###################### import datetime as dt import pandas import random import os import smtplib # 1. Update the birthdays.csv NAME = "[NAME]" def send_email(content): my_email = "testemailsonlynojoke@gmail.com" password = "1234abcd()" with smtplib.SMTP("...
from tkinter import * def button_clicked(): text = input.get() if text != "": my_label.config(text=text) window = Tk() window.title("My First GUI Program") window.minsize(width=500, height=300) # Add paddings among widgets window.config(padx=20, pady=20) # Label my_label = Label(text="I Am a Label", ...
from turtle import Screen, Turtle import time from snake import Snake # https://docs.python.org/3/library/turtle.html screen = Screen() screen.setup(width=600, height=600) screen.bgcolor("black") screen.title("My Snake Game") # animate snake segments: turn animation off, screen will refresh when .update() screen.trace...
from turtle import Turtle MOVING_DISTANCE = 20 class Ball(Turtle): def __init__(self): super().__init__() self.penup() self.shape("circle") self.color("white") self.x_move = 10 self.y_move = 10 # initial. speed self.move_speed = 0.1 def move(sel...
class Animal: def __init__(self): self.num_eyes = 2 self.legs = 4 def breathe(self): print("Inhale, exhale") # inheritance class Fish(Animal): def __init__(self): # inherit all attributes and methods from Animal class # The call to super() in the initialiser is reco...
class User: def __init__(self, name): self.name = name self.is_logged_in = False def is_authenticated_decorator(function): def wrapper(*args, **kwargs): if args[0].is_logged_in == True: # the function here refers to create_blog_post a function...
# -*- coding: cp1252 -*- #Importar el mdulo socket para abrir el canal de comunicacin import socket #Funcin principal def main(): localIP = "127.0.0.1" #Direccin IP del servidor localPort = 20001 #Puerto del servidor bufferSize = 1024 #Tamao del buffer msgFromSer...
#!/usr/bin/env python # coding: utf-8 import re import sys sys.path.insert(0,'..') from advent_lib import * PATH = 'input.txt' def process_line(line): data = re.split('\s|-', line.replace(':', ''))[:-1] data[0] = int(data[0]) data[1] = int(data[1]) return data def check_1(minn, maxx, key, password...
import turtle from random import * t = turtle.Turtle() # turtle객체를 t로 지정한다. t.speed(0) def circleDraw(t, r, f, n) : # 원을 그리는 함수 정의 시작. circleDraw(터틀객체, 반지름, forward이동거리, 원의 수) turtle.colormode(255) for i in range(1, n+1) : # 1부터 매개변수 n까지 반복하는 반복문 시작 t.pencolor(randint(0,255), randint(0,255), randint(0,2...
import turtle t = turtle.Turtle() # turtle객체를 t로 지정한다. def circleDraw(t, r, f, n) : # 원을 그리는 함수 정의 시작. circleDraw(터틀객체, 반지름, forward이동거리, 원의 수) for i in range(1, n+1) : # 1부터 매개변수 n까지 반복하는 반복문 시작 t.circle(r) # 반지름 r의 원 그리기 t.forward(f) # f만큼 이동 circleDraw(t, 50, 40, 4) # Test case 1 t.penup() t.got...
string=str(input()) words=string.split(' ') print(words) arr=[] for i in words: p=i[::-1] arr.append(p) print(*arr)
def distance(s1, s2): ''' >>> distance("cheese", "cheeso") 1 >>> distance("kitten", "sitting") 3 >>> distance("coffee", "coffee") 0 >>> distance("foo", "bar") 3 >>> distance("robot", "robotnik") 3 ''' if len(s1) == 0: return len(s2) if len(s2) == 0: return len(s1) if s1[-1] == s2[-1]: cost = 0 else: ...
# TIme complexity --> O(n logk) where n is the length of the nums #space complexity --> O(k) // Did this code successfully run on Leetcode : Yes // Any problem you faced while coding this : None Description: we create a minheap with k elements and then try to insert the other elements if they are greater than least ele...
def LongSubstr(st): if len(st)==0: return 0 max_lst=[] s=set() # s={} this notation creates an empty dictionary # Be cautious of sets and dict for char in st: s.add(char) for i in range(0,len(st)-len(s)): x=set() x.update(st[i:i+len(s)]) max_lst.appen...
"""Customer Class""" import random import pandas as pd class Customer: """a single customer that moves through the supermarket in a MCMC simulation.""" STATES = ['checkout', 'dairy', 'drinks', 'entrance', 'fruit', 'spices'] TPM = pd.read_csv('tpm.csv', index_col=[0]) def __init__(self, name, sta...
#!/usr/local/bin/python #Do a 1-D random walk and print the simple random walk #resulting from keeping a running sum of the value #of a random variable Z that is -1 or +1 with equal #probability. # Random walk: random variable Z is -1 with P = 0.5 # 1 with P = 0.5 # Simple rando...
#!/usr/bin/python """ This is the code to accompany the Lesson 1 (Naive Bayes) mini-project. Use a Naive Bayes Classifier to identify emails by their authors authors and labels: Sara has label 0 Chris has label 1 """ import sys from time import time sys.path.append("..\\tools") from email_...
print("Everyone loves baseball! Go blue jays!") print("Welcome to the slugging percentage calculator!") name = raw_input("Enter the player's name: ") singles = float(input("Enter the number of singles " + name + " has hit: ")) doubles = float(input("Enter the number of doubles " + name + " has hit: ")) triples = float(...
def is_cross(a, b): return (a[1] < b[3] and a[3] > b[1] and a[2] < b[0] and a[0] > b[2]) result = is_cross([-5, 2, 3,-2], [2, 6, 5, 1]) print(result)
import math def jump_search(arr, n, x): step = math.sqrt(n) prev = 0 while (arr[min(step, n) < x]): prev = step; step += math.sqrt(n) if (prev >= n): return False while (arr[prev] < x): prev = prev + 1 if (prev == min(step, n)): return False if (arr[prev] == x): retur...
''' class Myclass: x = 5 p1 = Myclass() print(p1.x) class Person: def __init__(self, name, age): self.name = name self.age = age def myfunction(self): print("My name is ", self.name + " and I am ", self.age,".") p1 = Person ("Jhon",38) p1.myfunction() p2 = Person ("sam",42) p2.myfuncti...
import tkinter as tk class Calculator(tk.Tk): def __init__(self): super().__init__() self.final_value = 'h' self.label_text = tk.StringVar() self.label_text.set('hello') self.label = tk.Label(self, textvariable=self.label_text, bg='white', fg='black', font=('arial', 25), re...
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1, l2, c = 0): result = None while l1 and l2: l3 = ListNode((l1.val + l2.val + c) % 10) c = int((l1.val + l2.val + c)...
q = 0 while q < 10: q = q + 1 print(q) if q == 6: continue
names = [ 'John', 'Jack', 'Jimmy', 'V', 'Chinu', 'Wosimosi' ] print( names ) print( names[3] ) names[3] = 'Diana' print( names ) #-------------For loop-------------- for name in names: print(name) for name in names: greeting = 'Hi ' + name print(greeting) for name in n...
''' Cities on a map are connected by a number of roads. The number of roads between each city is in an array and city is the starting location. The number of roads from city to city is the first value in the array, from city to city is the second, and so on. How many paths are there from city to the last city in...
# Reads CityPop, stores it in dictionaries, finds the population of a city # at a specific year import csv import os.path filename = 'CityPop.csv' # Make city_data into list city_data = [] # If filename is bad, tell the user if not os.path.isfile(filename): print("File does not exist.") # Open CityPop using Di...
""" A multiclass classification CNN model in tensorflow-2 using Dropout and BatchNormalization. Also data augmentation is used here. """ #Import libraies.............. import tensorflow as tf import numpy as np from sklearn.metrics import confusion_matrix import itertools import matplotlib.pyplot as plt from tensorfl...
#sudo pip install Theano import theano import theano.tensor as T import numpy from theano import function #Variables 'x' and 'y' are defined x = T.dscalar('x') # dscalar : Theano datatype y = T.dscalar('y') # 'x' and 'y' are instances of TensorVariable, and are of dscalar theano type print(type(x)) prin...
# Tuples = Lists ; but in tupe it can't be changed like how we can in lists... It is a sequence of Immutable Python objects. # Tuples use Parentheses (or comma), whereas lists use square-brackets. num_list=[1,3,6,8,4] print(num_list) num_list[1] = 2 print(num_list) print (len(num_list)) num_tuple= 1,3,6,8,4 print(n...
# Count the number of prime numbers less than 2000 and time it. import time as t start = t.clock() primes = [2,3,5,7] for num in xrange(2,200000): if all(num%x != 0 for x in primes): primes.append(num) print primes print (t.clock() - start, "Seconds.") print (len(primes), "Primes") print (sum(primes),...
# Implement a tuple of elements of all the 4 different data types, 3 examples of each type :- # str # bool # int # float int_tuple= 1,2,6,8,4 print(int_tuple) str_tuple= "lively","alone","friends","enemies" print(str_tuple) bool_tuple = True,False,None print(bool_tuple) float_tuple =...
# Dictionary is a set of key-value pairs. # It is enclosed in curly braces (or flower brackets). a = {1:'number one', 22 : 'number twenty-two'} # Here 1 and 22 are keys and 'number one' and 'number twenty-two' are their values respectively. print(a) print(a[1]) print(a[22]) dict_employee = {"Employee_name": "Ravi...
# concept - Loops => 1.While loop count=0 while count <= 100: # Condition if count%10==0 : print (count) count = count + 1 print ("\n") count=0 while count <= 100: # Conditi...
""" email_alerts.py Eva Grench, 22 February 2018 Sends an html email from the server with a table of all the rules that had anomalous values, the number of anomalous values under that rule, and a link to view the results on the anomalies dashboard. It is sent to a google group. """ import os from...
a = int(input()) print(a >= 10 and a <100) print(10 <= a < 100)
a = int(input()) b = int(input()) c = int(input()) if a > b and a > c: max = a if b > c: mid = b min = c else: mid = c min = b print(max) print(min) print(mid) elif b > a and b > c: max = b if a > c: mid = a min = c else: mid =...
x=str(input("enter the char : ")) i=( x>='a' and x<'z')or(x>='A' and x<='Z') if(i): print("alphabet") else: print("no")
from tkinter import * from tkinter import ttk import tkinter.font as tkFont import time class SampleTkinterLoop: def __init__(self, master): # Initialize master as the Tk() instance self.master = master master.title("Loop Tests") master.config(background="#e8ecf2") master....
import RPi.GPIO as GPIO ## Import GPIO library import time ## Import 'time' library. Allows us to use 'sleep' GPIO.setmode(GPIO.BOARD) ## Use board pin numbering GPIO.setup(7, GPIO.IN) ## Setup GPIO Pin 7 to OUT inp = GPIO.input(7) while True: if GPIO.input(17): print "button pressed"
# ----------------------------------------------------------- # prompts a user to input their specification and returns the object of their input. # (C) 2020 Mahmudul Alam # Released under Colorado State University-Global Campus # email mahmudul.alam@csuglobal.edu # ------------------------------------------------...
# coding: utf-8 # In[95]: import csv import pprint import re import codecs import xml.etree.cElementTree as ET import json from collections import defaultdict import unicodedata # In[96]: # the OSM data file OSM_FILE = "hochiminh_city.osm" # the JSON file JSON_FILE = "hochiminh_city.json" # In[97]: ''' Functi...
import turtle from random import * s=1 while (s>0): turtle.forward(20) turtle.left(randint(0, 360))
#!/usr/bin/env python def calc_birthday_prob(n): ''' Calculates the probability of at least two people in a group of size n having the same birthday. INPUTS: n (integer): number of people in the group OUTPUTS: p (float): probability of matching birthday ''' prob = 1 for x in range(1,...
def is_permutation(str1, str2): if len(str1) != len(str2): return False myList1 = [] myList2 = [] for i in range(0, len(str1)): myList1.append(str1[i]) myList2.append(str2[i]) myList1.sort() myList2.sort() if myList1 == myList2: return True return False...
numberOfPeople = raw_input("How many people are coming: ") pizzaPrice = 10 juicePrice = 10 costPerPerson = pizzaPrice + juicePrice totalCost = int(numberOfPeople) * costPerPerson print totalCost