text
stringlengths
5
121k
import math print("This is the program to find the square root of a number:") num=int(input("Enter a number:")) sqrt=math.sqrt(num) print("Square root of "+ str(num)+ " is \n" , sqrt)
print("\t\t\t\t\tThis is a program to automate a Billing System\n\n\n") pre_mon=int(input("Enter the Previous Month Home Units: ")) cur_mon=int(input("Enter the Current Home Month Units: ")) ac1=int(input("Enter the Previous A.C Month Units: ")) ac2=int(input("Enter the Current A.C Month Units: ")) print("Home Uni...
print("This isa program to convert temprature in celcius to farenheight") temp_cel=float(input("Enter the temprature in Celsius:")) temp_faren= (temp_cel*1.8) +32 print("Temprature in Farenheight is:", temp_faren)
from math import sqrt a=float(input("Enter the length of side a:")) b=float(input("Enter the length of side b:")) h= sqrt(a**2 + b**2) newh=round(h, 2) print("The length of the hypotenuse is", newh)
x=int(input("enter the number")) if(x>0): print("positive number") elif(x==0): print("zero") else: print("nagative number")
foods=('potato','tomato','french fries','beef','pork') for food in foods: print("delicious"+food+'!') foods=('potato','tomato','fish','noodles','pork') for food in foods: print("delicious"+food+'!') foods[0]="ricea"
class Car(): """一次模拟汽车的尝试""" def __init__(self,make,model,year): """初始化描述汽车的属性""" self.make=make self.model=model self.year=year self.odometer_reading=0 def get_descriptive_name(self): """返回整洁的描述性信息""" long_name=str(self.year)+' '+self.make+' '+self....
def city_country(city,country,population=''): if population: return city+','+country+'-'+'population:'+str(population) else: return city+','+country
def func(a): a = str(a) s = 0 for c in a: s += int(c) return s for x in range(100, 1001): flag = True for y in range(3, 8): if func(y*x) != func(3*x): flag = False break if flag: print(x)
def judge(password): degree = 0 for c in password: if c.isdigit(): degree += 1 break for c in password: if c.isupper(): degree += 1 break for c in password: if c.islower(): degree += 1 break ...
alien_0={'color':'green','points':5} alien_1={'color':'yellow','points':10} alien_2={'color':'red','pinots':15} aliens=[alien_0,alien_1,alien_2] for alien in aliens: print(alien) aliens=[] for alien_number in range(30): new_alien={'color':'green','points':5,'speed':'slow'} aliens.append(new_alien) for alien...
cars=['AUDI','Toyota','bmw','honda','beijing','jeep','beiJING'] for car in cars: if car=='bmw': print(car.upper()) else: print(car.title()) if car.lower()=='audi' or car.upper()=='TOYOTA': print(car.title()) if car.lower()=='beijing' and car!='beiJING': print(car) if 'hon...
while True: try: pilha = input() correct = 1 par = 0 i = 0 while i < len(pilha) and correct: if pilha[i] == '(': par += 1 if pilha[i] == ')': if par == 0: correct = 0 else: par -= 1 if i == len(pilha)-1: if par % 2 != 0: correct = 0 i += 1...
pi = 3.14159 radius = float(input()) A = pi*radius**2 print('A={:.4f}'.format(A))
N = int(input()) for i in range(N): X = int(input()) is_prime = 1 aux = 2 while is_prime == 1 and aux < X: if X % aux == 0: is_prime = 0 else: aux += 1 if is_prime == 1: print('{} eh primo'.format(X)) else: print('{} nao eh primo'.format...
class Node: def __init__(self, priority, puzzle_state): self.priority = priority self.puzzle_state = puzzle_state def __repr__(self): return f'({self.priority}, {self.puzzle_state})' class PriorityQueue: """ Minimum Priority Queue """ def __init__(self)...
n=ord('a') while(n<123): print(chr(n)) n=n+1
s1 = []; s2 = []; def eq(x): s1.append(x) def dq(): if (len(s2) == 0): if (len(s1) == 0): return 'Cannot dequeue because queue is empty' while (len(s1) > 0): p = s1.pop() s2.append(p) return s2.pop() eq('a'); eq('b'); eq('c'); dq(); print(s1)...
n=input() n=list(n) s=0 for i in n: s=s+ord(i) if(s%8==0): print("1") else: print("0")
n=input() """if we give n=input().split() wont work for guvi but will work for g*u*v*i then give input().split(*)""" """for i in range(0,len(n)): n[i]=n[i].upper() print(n)""" """for i in n: print(i.upper())""" n=list(n) for i in range(0,len(n)): n[i]=n[i].upper() a="...
s="string***" print(s.rstrip("*")) print(s.lstrip("str")) print(s.strip("***")) print(s.strip("str")) a=s.replace("***","") print(a) x="this***is***test" print(s.replace("***"," "))
l=[] l.append(2) l.append(3) print(l) x=l.copy() print(type(x)) print(x) l.clear() print(l) l=[2,2,3,4,'a'] print(l.count('a')) x=(5,) l.extend(x) print(l) print(l.index(5)) l.insert(5,'b') print(l) l.pop(1) print(l) l.insert(1,2) l.remove(2) print(l) l.reverse(...
""" module principale du programme """ from tkinter import * import os def main(): def entrer(): root.destroy() os.system("python gui/ajouter.py") def afficher(): root.destroy() os.system("python gui/afficher.py") def rechercher(): root.destroy() os.s...
def walk_together(*readers): """ Walk a set of readers and return lists of records from each reader, with None if no record present. Caller must check the inputs are sorted in the same way and use the same reference otherwise behaviour is undefined. """ nexts = [reader.next() for ...
class State: def __init__(self, A, B, C, Result): self.s = [A, B, C] self.res = Result self.same = True if A == B == C else False def can_move(state, II, J): p = state.s[II] lis = [0, 1, 2] lis.remove(II) return map_[p][J] == map_[state.s[lis[0]]][state.s[lis[1]]] or \ ...
'''n=int(input("enter the number : ")) print("normal number print with for and range function") for i in range(n): print(i) # ============================================================================================================================= # print number with space print("print horizontal wit...
'''a=int(input("enter the first no :")) b=int(input("enter the second no :")) print(a/b)''' '''try: a=int(input("enter the first no :")) b=int(input("enter the second no :")) print(a/b) except: print("enter the correct number ")''' '''try: a=int(input("enter the first no :")...
""" Main program to set up and run a uno game. """ from uno_deck import Deck, PlayGame from uno_view import TextView from uno_controller import TextController def main(): """ Play a game of uno """ print("Welcome to Uno!\n \ Here are the rules:\n \ 1. Match the card in the middle ...
""" Daily Coding Problem #13 Given an integer k and a string s, find the length of the longest substring that contains at most k distinct characters. For example, given s = "abcba" and k = 2, the longest substring with k distinct characters is "bcb". """ def substringLength(k, s): start = 0 end = 1...
""" Daily Coding Problem #6 An XOR linked list is a more memory efficient doubly linked list. Instead of each node holding next and prev fields, it holds a field named both, which is an XOR of the next node and the previous node. Implement an XOR linked list; it has an add(element) which adds the element to the e...
''' #rows for i in range(0,5): #columns for j in range(0,i+1): print ('*', end ='') print ('\r') ''' def half_pyramid(num_r): for i in range(0,num_r): for j in range(0,i+1): print ('*', end ='') print ('\r') def tree_log(log_length,log_width): ...
import sys i = 0 total = 0 args = sys.argv[1:] while i < len(args): total = total + int(args[i]) i = i + 1 print(total)
import sys words = sys.stdin.readlines() fruits = { "apple": True, "pear": True, "orange": True, "banana": True, "cherry": True, } i = 0 while i < len(words): if words[i].strip() in fruits: print(words[i].strip()) i = i + 1
x = (x * -1) if x <= 0: x = x - 1 else: x = x + 1
n = 10 i = 0 while i < n: num = int(input()) if i == 0: num10 = num elif i == 1: num9 = num elif i == 2: num8 = num elif i == 3: num7 = num elif i == 4: num6 = num elif i == 5: num5 = num elif i == 6: num4 = num elif i == 7: ...
n = 10 i = 0 total = 0 while i < n: numIn = int(input()) numIn = ((numIn + 1) % 2) * numIn total = total + numIn i = i + 1 print(total)
A = input() B = input() C = input() if (len(A) > len(B) and (len(A) > len(C))): print(A) elif (len(B) > len(A) and (len(B) > len(C))): print(B) else: print(C)
timetable = [] s = input() while s != "end": timetable.append(s) s = input() i = 0 while i < len(timetable): tokens = timetable[i].split() print(tokens[3]) i = i + 1
num = int(input()) x1 = num // 100 x2 = (num // 10) - (x1 * 10) x3 = (num) - ((num // 10) * 10) print(x1) print(x2) print(x3)
''' Hand keeps track of cards on hand and total value of them ''' class Hand(): def __init__(self, initial_cards = []): self.cards = initial_cards def __str__(self): return f'{self.cards}' def get_card_info(self,hidden_cards = 0): card_list = self.cards for i in range(hidd...
def solution(s): for count in range(len(s),1,-1): for i in range(len(s)-count+1): target = s[i:i+count] palindrome = True for j in range(count//2): if target[j] != target[(j+1) * (-1)]: palin...
result = 0 def fun_fuction(m, n): if 0 < m or m < n: return "Wrong input" else: Variable_to_save_m = m Variable_to_save_n = n global result if m == n or m == 0: result += 1 else: if 0 < m and m < n: fun_fuction(m - 1, n - 1) fun_fuction(Variable_to_save_m, Variable_to_save_n - 1) return r...
def to_arabic (k): k+=" " result=0 dictionary_={"M":1000,"D":500,"C":100,"L":50,"X":10,"V":5,"I":1," ":0} J=list(dictionary_.keys()) for x in range(len(k)-1): if J.index(k[x])<=J.index(k[x+1]): result+=dictionary_.get(k[x]) else: result-=dictionary_.get(k[x]) if result<=3000 and result>=1: pr...
import pandas as pd urldata = 'https://raw.githubusercontent.com/emanuelgit/Python_Program_BI/master/data/titanic/titanic3.csv' data = pd.read_csv(urldata) text = 'Curso\n\tPython' print(text) name = input("Name : ") surname = input("Surname : ") edad = input("edad:") print("Thanks,", name, surn...
def dog_check(mystring): if 'dog' in mystring: return True else: return False a = dog_check("hey this is dog") print(a) def dog_checks(my_string): if 'dogy' in my_string: return True else: return False b = dog_checks("hey this is dogyy") print(b) def pig...
ask = input("Enter your expression: ") def variables(s): chrList = ['(',')','+','-','*','/','0','1','2','3','4','5','6','7','8','9'] if s in chrList: return True else: return False def jisuan(n1,n2,o): if o=='+': return n1+n2 elif o=='-': return n1-n2 elif o=='*'...
semiperimetro_del_triangulo=float(input("ingrese el semiperimetro del triangulo:")) radio_del_circulo=float(input("ingrese el radio del circulo:")) area_del_triangulo=(semiperimetro_del_triangulo*radio_del_circulo) area=(area_del_triangulo>75) print("el area del triangulo que circunscribe a un circulo es...
cliente=(input("ingrese el nommbre del cliente: ")) precio_mochila=float(input("ingrese el precio de la mochila:")) numero=int(input("numero de mochilas:")) total=(precio_mochila*numero) cliente_necesario=(total>120) print("############################") print("# BOLETA DE VENTA") print("##############...
if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) current = min(arr) for i in range(0, n): if arr[i] > current and arr[i] < max(arr): current = arr[i] print(current)
st = 'Sam Print only the words that start with s in this sentence' for n in st.split(): if n[0].lower() == 's': print (n)
def triangle(position, x0, x1, x2, clip=1): value = 0.0 if x0 <= position <= x1: value = (position - x0) / (x1 - x0) elif x1 <= position <= x2: value = (x2 - position) / (x1 - x0) if value > clip: value = clip return value def grade(position, x0, x1, clip=1): if p...
import matplotlib.pyplot as plt import pandas as pd import numpy as np from sklearn.cluster import KMeans from sklearn.preprocessing import LabelEncoder data= pd.read_csv("part-r-00000.csv",header=None) z=LabelEncoder() kmeans =KMeans(n_clusters=3) data["numerical"]=z.fit_transform(data[0]) l=data[["numerical",2]] kmea...
import numpy as np import matplotlib.pyplot as plt from sklearn.preprocessing import LabelEncoder from sklearn.cluster import KMeans import pandas as pd data = pd.read_csv("part-r-00000.csv",header=None) lbmake =LabelEncoder() data["numerical"]=lbmake.fit_transform(data[0]) print(data) x=data[["numerical",1]] kmeans=KM...
""" Author : Vishal Panchal Created At : 9 August 2019 Description : This is sample flask application with sample API to create to do list. """ from flask import Flask, request, jsonify, render_template,redirect from controller import TaskController import os app = Flask(__name__) app.config["DEBUG"] = True @...
balance = 150 annualInterestRate = 0.2 def calculator (x, r, n, p): """ Inputs: x = initial balance r = annual interest rate Outputs: The monthly fixed payment to reduce x to <=0 in 12 months """ for n in range(0,12): if (n == 0): balUnpaid = x - p ...
balance = 999999 annualInterestRate = 0.18 lowerBound = balance / 12.0 upperBound = balance def calculator (x, r, n, p, l, u): """ Inputs: x = initial balance r = annual interest rate n = month counter p = fixed payment guess, starting with mid of two bounds l = lower bound h = upper ...
def keysWithValue(aDict, target): ''' Inputs: aDict: a dictionary target: an integer Outputs: L: a list of keys mapped to the target, sorted in ascending order ''' L = [] for key in aDict.keys(): if (aDict[key] == target): L.append(key) ...
import random import pylab as plt MAXRABBITPOP = 1000 CURRENTRABBITPOP = 50 CURRENTFOXPOP = 300 def rabbitGrowth(): """ rabbitGrowth is called once at the beginning of each time step. It makes use of the global variables: CURRENTRABBITPOP and MAXRABBITPOP. The global variable CURRENTRABBITPOP is m...
def isIn(char, aStr): ''' char: a single character aStr: an alphabetized string returns: True if char is in aStr; False otherwise ''' if (len(aStr) == 0): return False index = len(aStr) // 2 guess = aStr[index-1] if (len(aStr) == 1): return guess == char ...
for i in range(1, 101): str_i = str(i) count_str = 0 for j in str_i: if (j =='3') or (j =='6') or (j =='9'): count_str = count_str+1 if count_str == 0: print(str_i+':', i) else: print(str_i+':', count_str * '짝')
print("3개의 값을 입력하시오") x = int(input("Enter the x: ")) y = int(input("Enter the y: ")) z = int(input("Enter the z: ")) z = x + 1 y = y + 1 x = z + 1 print("변경된 값 : ", x, y, z)
import colors as c print('c.clear') print(c.blue + 'what is your name' + c.reset) person = input('enter your name') print('nice to met you' + person)
import random import time class Introduce: Bleeps = ["&","#","$","-","*","+","@","_"] def MyselfAs (name): print("Hi! I'm " + str(name)) time.sleep(2) print("I am a self taught programmer, who's only goal is to get better") time.sleep(2) print("I have made a few project...
N = input() sum_integer = 0 for i in range(N): sum_integer=sum_integer+numArray[i-1] print(sum_integer)
def add(): return 1 + 1 def beforeFunction(func): print("This is the function before add()") print(func()) beforeFunction(add)
veg_dict={'Brinjal':10,'Cabbage':20,'Pumpkin':25} print("-------------------\n") choice=0 while choice != 5 : print("1.View list\n2.Add a new vegetable\n3.Change the price of an vegetable\n4.Delete the vegetable\n5.Quit!") print("-------------------\n") choice=int(input("Enter your choice ")) ...
from cs50 import get_float change = 0.00 quarters = 0.25 dimes = 0.10 nickels = 0.05 pennies = 0.01 coins = 0 while True: change = get_float("Change owed:") if change > 0.00: break while(change >= quarters): change = change - quarters coins += 1 while( change >= dimes): change = change - dim...
"""Matrix: Special case of two dimensional array where each data element is of strictly the same size. These are important for some mathematical and scientific calculations.""" from numpy import * a = array([['Mon',18,20,22,17],['Tue',11,18,21,18], ['Wed',15,21,20,19],['Thu',11,20,22,21], ['F...
or__ = 'bruno' class AddressBookGUI(object): """ This is the parent class of AddressBookImportDialogue, AddressBookEntryDialogue and AddressBookDialogue, it holds methods and variables that are shared among the two children classes """ def __init__(self): """ Does things, and t...
ali_age = int(input('Input Ali Age:')) sara_age = int(input('Input Sara Age:')) if ali_age == sara_age: print('They both have same age') elif ali_age < sara_age: print('Ali is younger than Sara') else: print('Ali is elder than Sara')
import random def is_prime(n): if n < 1: return False for i in range(2, int(n / 2)): if n % i == 0: return False return True def gcd(a, b): while (a != 0) and (b != 0): if a > b: a = a % b else: b = b % a return a + b def m...
PLAYERS={False:'X',True:'O'} def creation(length): return [[1+q+i*length for q in range(length)] for i in range(length)] def display(kek): for i in kek: for q in i: print('{:>5}'.format(q),end="") print() def innit(): while True: try: kek = int(input("Input...
matrix=[ [1], [0], [0] ] matrix2=[ [0,-1,0], [1,5,0], [0,0,0] ] class Matrix: def __init__(self, val): if(type(val)==list): self.val = val else: self.val=-1 def __eq__(self, other): return self.val == other.val def __repr__(self): return self.val def __mul__(self, other): if(type(self)==type(o...
numbers = [1,2,3,4,5,6,7,8,9,10] def EvenFunction1(): evenList = [] for number in numbers: if number % 2 == 0: evenList.append(number) print(numbers) print("Even Number List is {}".format(evenList)) def OddFunction1(): oddList = [] for number in numbers: if number...
def function1(): print("Inside Function 1") def function2(func): print("Inside Function 2 ") func() print(type(func)) def add(num1, num2): print(num1+num2) def sub(num1, num2): print(num1-num2) def mul(num1, num2): print(num1*num2) def div(num1, num2): print(num1/num2) def ...
""" Read file into texts and calls. It's ok if you don't understand how to read files """ import csv import datetime from datetime import timedelta with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader...
import random answers = ( "Go for it" "No way, Jose!" "I'm not sure. Ask me again." "Fear of the unkown is what imprisons us." "It would be madness to do that." "Only you can save mankind!" "Makes no difference to me, do or don't - whatever" "Yes, I think on balance that is the righ...
def absolute(n): if(n >= 0): return n return -n def palindrome4(input): if(len(input) > 4 or len(input) < 4): return False string = input[::-1] if(string == input): return True return False def ORF(DNA): beginning = DNA[:3] ending = DNA[-3:] if(beginning ==...
from encryption import * from decryption import * def get_path_to_file(): path_to_file = input("Введите путь до файла: ") return path_to_file def get_file_password(): password = input("Введите пароль: ") return password def choose_the_action(): choose = input("Выберите\nЗашифровать/расшифроват...
class Person(object): def __init__(self, name, education): self.name = name self.education = education def work(self): print("%s goes to work" % self.name) test_person = Person('Generic name', 'bachelors degree') test_person.work() class Employee(Person): def __init__(self, nam...
import basic_graphics import math def draw(canvas, width, height): t = math.pi / 2 n = 5 dt = 3 * (2 * math.pi) / n r = 100 x = width / 2 y = height / 2 canvas.create_oval(x-r, y-r, x+r, y+r) x0, y0 = x, y - r for i in range(n+1): canvas.create_oval(x0-5, y0-5, x0+5, y0+5) ...
import random def randInt(min=0 , max= 100 ): num = random.random() * (max-min) + min return round(num) print(randInt(20)) print(randInt(20,100)) print(randInt(max=20, min=10)) print(randInt(40))
from Organization import Org from NeuralNet import NeuralNet def main(): """ Kieran Ringel For each data set three lines are run in main. The first one creates an instance of Org with the arguments being the file name, where the header is located to be removed ([-1] if there is no header, the location o...
import random import cProfile from memory_profiler import profile @profile def FindDuplicates(numbers): counter = 0 if len(numbers) < 2: return counter else: numbers.sort() dup = 0 for i in range(1,len(numbers)): if ((numbers[i-1] == numbers[i]) & (dup == 0)): counter = counter + 1 dup = 1 e...
from window import Window import utils import curses ''' The menu window ''' class Menu(Window): def __init__(self, h, w, options, stdscr): Window.__init__(self, stdscr, False) self.options = options self.h = h self.w = w self.selectedOption = 0 self.stdscr ...
from os import listdir from os import path def get_pet_labels(image_dir): """ Creates a dictionary of pet labels (results_dic) based upon the filenames of the image files. These pet image labels are used to check the accuracy of the labels that are returned by the classifier fu...
class SQLTable: class Attribute: def __init__(self, tName, aName, aType, aLimit=None,): self.attName = aName self.attType = aType self.attLimit = aLimit self.tbName = tName self.attData = [] def __str__(self): if self...
temp = float(input('Enter the temperature in degrees Fahrenheit: ')) Cel = (5/9)*(temp-32) line = 'The temperature in degrees Celsius is' print(line, Cel)
n = int(input("Please specify a positive integer n:")) print("These are the squares of all numbers from 0 to n-1:") for i in range(n): print(i*i)
def leftRotate(arr, d, n): print("leftRotate() | 15:21 21F19") for i in range(d): leftRotatebyOne(arr, n) def leftRotatebyOne(arr, n): print("leftRotatebyOne() | 15:23 21F19") temp = arr[0] for i in range(n-1): arr[i] = arr[i + 1] arr[n-1] = temp def leftRotate_Juggl...
class Node: print("Node class") def __init__(self, data): self.data = data self.next = None class LinkedList: print("LinkedList Class") def __init__(self): self.head = None def printList(self): print("printList() - start | 19:25 19F19") ...
class ViewAngles: pitch: float yaw: float roll: float def __init__(self, pitch: float, yaw: float, roll: float): self.pitch = pitch self.yaw = yaw self.roll = roll def __str__(self): return "pitch: " + str(self.pitch) + "\\nyaw: " + str(...
import turtle def Recursive_Koch(length, depth): if depth == 0: turtle.forward(length) else: Recursive_Koch(length, depth-1) turtle.right(60) Recursive_Koch(length, depth-1) turtle.left(120) Recursive_Koch(length, depth-1) turtle.right(60) Recursive_Koch(length, depth-1) turtle.speed(0) turtle.bac...
import turtle SPIRAL = True def curve(t, length, depth, sign): if depth == 0: for turtle in t: turtle.forward(length) else: curve(t,length, depth-1, 1) for turtle in t: turtle.right(90*sign) curve(t,length, depth-1, -1) if __name__ == '__main__': heading = 0 colors = ['purple', 'red...
def mabs(num): if not isinstance (num,(int, float)): print("typeErro we need Interge or Float ,but you give me s%" ,type(num)) return; if num>0: return num; else: return -num;
name = input ("enter a name"); weight = float(input("enter your weight in kilograms(kg) : ")); height = float(input("enter your height in centimetres(cm): ")); bmi = weight /(height *height) print(bmi) print("%s has a BMI of: %10.7f"%(name,bmi))
for number in range ((30//5) +1) : if number == 0 : continue print (5*number)
class Relation(object): def __init__(self): self.cntrDB = [] self.cntrid = 0 self.ctDB = [] self.ctid = 0 self.lastid = 0 self.sortedDB = [] def add(self, cntrid, ctid, Countries, Cities): if cntrid > Countries.lastid or cntrid < 0: ...
class Price(object): def __get__(self, obj, objtype=None): return obj._price * obj._amount def __set__(self, obj, value): obj._price = value class Book(object): price = Price() def __init__(self, amount): self._price = 42 self._amount = amount book = Boo...
import nltk import pandas as pd pd.set_option('display.max_colwidth', 100) df = pd.read_csv('data/reddit_data.csv') print(df.head()) print(df.shape) print(df['num_comments'].describe()) print('Num of null in label: {}'.format(df['num_comments'].isnull().sum())) import string print(string.punctuation) def r...