text
stringlengths
5
121k
userRange = input("Hello, how many numbers would you like to enter? ") numbers = [0] * int(userRange) numbers[0] = 0 numbers[1] = 1 x = numbers[0] y = numbers[1] i = 0 range = int(userRange) sum = 0 while x < int(userRange): if x % 2 == 0: sum = sum + x z = x + y x = y y = z ...
import copy padrao = [] quadros = 0 while True: leitura =list(input("")) if(leitura[0].isnumeric()): quadros = int("".join(leitura)) break else: padrao.append(leitura) def imprimir_matriz (M): for i in M: print("".join(i)) def matriz (M): ...
def main(): dictionary = {"Book": "is something to read"} print(dictionary) biniam_data = { "name": "Biniam", "age": 32, "profession": "Senior Software Engineer", "spouse": { "name": "Kidan", "age": 29 } } print(biniam_data) ...
def main(): students = ["Kidu", "Hareg"] name = input("What is your name? ") if name not in students: print("You are not a student") else: print("You are a student") value = False if not value: print("Value is false") else: print(...
def main(): ageString = input('Please enter your age ') age = int(ageString) if age < 10: print('child') elif age >= 10 and age < 30: print('young') elif age > 30 and age <= 50: print('adult') else: ...
is_Tuesday = True is_Friday = True is_Monday = False is_Evening = True is_Morning = False if is_Monday: print("I have python class") else: print("I dont have python class") if is_Friday or is_Monday: print("I have python class") else: print("I dont have python class") if is_Friday and is_Evening: ...
dict = {} dict['a'] = 'alpha' dict['g'] = 'gamma' dict['o'] = 'omega' for key in dict: print(key, '->', dict[key])
import seaborn as sns from sklearn.datasets import load_boston import matplotlib.pyplot as plt import pandas as pd import numpy as np boston_dataset = load_boston() boston = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names) boston['MEDV'] = boston_dataset.target boston.head() prin...
def weight_on_planets(): earth = int (input("What do you weigh on earth? ")) print ("\nOn Mars you would weigh", earth*0.38, "pounds.") print ("On Jupiter you would weigh", earth*2.34, "pounds.") if __name__ == '__main__': weight_on_planets()
import sqlite3 import json from pprint import pprint def get_db(db_name): try: if db_name != "phonebook_database.db": raise OSError('Wrong database name!') conn = sqlite3.connect(db_name) c = conn.cursor() print('Yay! A none is not returned') ...
import sys, random assert sys.version_info >= (3,7), "This script requires at least Python 3.7" print('Greetings!') colors = ['red','orange','yellow','green','blue','violet','purple'] play_again = '' best_count = sys.maxsize while (play_again != 'n' and play_again...
""" Created on Fri Apr 17 00:25:14 2020 @author: Vasilis """ class Bike: def __init__ (self,color,price): self.color = color self.price = price testOne = Bike('blue',89.99) testTwo = Bike('purple', 25.0) print(testOne.color) class AppleBasket: def __init__ (self,apple_co...
""" Created on Sat Apr 18 00:03:34 2020 @author: Vasilis Important resouces not covered in the course abut modules unittest and doctest: https://docs.python.org/3/library/unittest.html https://docs.python.org/3/library/doctest.html#module-doctest Asser statement: https://docs.python.org/3/reference/simp...
""" Created on Thu Apr 30 19:49:51 2020 @author: Vasilis """ from PIL import Image, ImageDraw from ipywidgets import interact image=Image.open('readonly/storefront.png') @interact(left=100, top=100, right=200, bottom=200) def draw_border(left, top, right, bottom): img=image.copy() dra...
from datetime import datetime def parse_date(string_date): try: d = datetime.strptime(string_date, "%Y-%m-%d %H") except ValueError: d = datetime.strptime(string_date, "%Y-%m-%d") return d def date_to_string(date): d = datetime.strftime(date, "%Y-%m-%d %H") return d
import pandas as pd class CarInfoDb: def __init__( self, filename="/home/saharul/Projects/csa_ver3/data/carinfo_master.csv" ): self.dbfilename = filename def GetModelId(self, model): if type(model) != str: raise TypeError("Car Model must be in str") if len(mo...
x=1 if x<1: print("greater than 1") elif x==1: print("equal to 1") else: print("less than 1")
counter=100 miles = 1000.0 name = "John" print(counter) print (miles) print (name) print("----------------------------") a = b = c = 1 print(a) print(b) print(c) print("----------------------------") a, b, c = 1, 2, "john" print(a) print(b) print(c) print("----------------------------") s="abcdef" print(s[5...
import os script_dir = os.getcwd() odd_path = "oddlines.txt" even_path = "evenlines.txt" output_path = "output.txt" abs_odd_path = os.path.join(script_dir, odd_path) abs_even_path = os.path.join(script_dir, even_path) abs_output_path = os.path.join(script_dir, output_path) fodd = open(abs_odd...
import string class Hierarchy(dict): def is_derived_from(self, derived: string, base: string) -> bool: if derived not in self: return False if derived == base: return True for p in self[derived]: if p == base or self.is_derived_from(p, base): ...
import numpy as np import pandas as pd training_data = pd.read_csv("train.csv") from sklearn.metrics import * from sklearn.model_selection import train_test_split y = training_data['label'] X = training_data.drop(['label'], axis=1) X_train, X_test, y_train, y_test = train_test_split( X, y, test_s...
from cmu_112_graphics import * import math, random class MyApp(App): def appStarted(self): self.doorsList = [(3,6),(4,9),(5,17),(6,11),(6,12),(8,6),(9,17),(10,3), (12,1),(12,16),(15,5),(17,9),(17,14),(18,19),(19,4),(19,8),(19,15)] def pathfinding(self, start, ...
import os import sys, time def TicketsCalculation(): print("How many tickets do you have?") num_tickets = int(input()) if num_tickets < 4: print("We are able to proceed") else: print("We are unable to insure customers with more than 3 tickets") print("Thank you for your time") ...
import cv2 import numpy as np uppLeft = None lowLeft = None uppRight = None def mouseResponse(event, x, y, flags, param): """This function is a callback that happens when the mouse is used. event describes which mouse event triggered the callback, (x, y) is the location in the window where the event happ...
def string_length(str1): count=0 for char in str1: count = count+1 return count print(string_length("muskaan"))
KEY = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' ciphertext = input('Enter Cipher Text? ') def decrypt(x, ciphertext): result = '' for l in ciphertext: try: index = KEY.index(l) i = (index - x) % 26 result += KEY[i] except ValueError: ...
import re import sys def get_string(prompt) -> object: """ Read a line of text from standard input and return it as a string, sans trailing line ending. Supports CR (\r), LF (\n), and CRLF (\r\n) as line endings. If user inputs only a line ending, returns "", not None. Returns None upon error or n...
class Solution: def findAnagrams(self, s, p): """ :type s: str :type p: str :rtype: List[int] """ block = dict() winBlock = dict() returnList = list() for ch in p: block[ch] = block.get...
class Solution: def countUnivalSubtrees(self, root: TreeNode) -> int: self.count = 0 def dfs(root): if root == None: return True left = dfs(root.left) right = dfs(root.right) if (left == right): if (root.left != ...
class Solution: def trap(self, height): """ :type height: List[int] :rtype: int """ if height == []: return 0 ans = 0 length = len(height) leftMax = [0 for...
class Solution: def myAtoi(self, s: 'str') -> 'int': """ :type str: str :rtype: int """ ls = list(s.strip()) if len(ls) == 0: return 0 if len(s) == 0: return 0 if ls[0] == '-': sign = -1 else: si...
class Solution: def findDuplicate(self, nums: List[int]) -> int: if (len(nums) > 1): slow = nums[0] fast = nums[0] while (fast != None and slow != None): slow = nums[slow] fast = nums[nums[fast]] if fast...
import sys class Solution: def lengthOfLongestSubstringTwoDistinct(self, s): """ :type s: str :rtype: int """ left = 0 right = 0 ...
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def middleNode(self, head: ListNode) -> ListNode: pointer1 = head pointer2 = head while (pointer2 != None and pointer2.next != None): pointer1 = pointer1.next po...
class Solution: def addDigits(self, num): """ :type num: int :rtype: int """ sum = 0 for ch in str(num): sum = sum + int(ch) if sum<10: return sum else: return self.addDigits(sum)
from abc import ABC, abstractmethod class ImpostosAbstrato(ABC): @abstractmethod def calcula(self): pass class ICMS(ImpostosAbstrato): def calcula(self, valor): return valor * 0.11 class ISS(ImpostosAbstrato): def calcula(self, valor): return valor * 0.05 class PIS(Imp...
class Result: """ A class used to represent a rated task. Attributes ---------- checkbox_results : list list of the rated attributes using Yes/No chekboxes slider_results : list list of the rated attributes using a slider with values in [0,100] Methods ------- ...
class MenuBuilder: """Menu builder""" menu="" selection=None def __init__(self, logger, items): self.logger = logger self.logger.name = self.__class__.__name__ self.items = items def display(self): index = 1 self.menu = "Please select a connection:\n" for item in self.items: self.menu += str(index...
uurloon = input('Uurloon: ') werkuren = input('Aantal werkuren: ') int(uurloon) int(werkuren) salaris = int(werkuren)*int(uurloon) print('Je verdient: ' + str(uurloon) + ' per uur') print('Je hebt: ' + str(werkuren) + ' uren gewerkt') print(str(werkuren) + ' uur levert ' + str(salaris) + ' Euro op')
numbers = [3, 6, 4, 1, 7, -2] for i in numbers: if i % 2 == 0: print(i)
from mapreduce import MapReduce class WordCount(MapReduce): def mapper(self, _, line): for word in line.split(" "): yield (word.strip(),1) def combiner(self, key, values): yield key, sum(values) def reducer(self, key, values): yield key, sum(values) with ope...
import pandas squirrel_data = pandas.read_csv('2018_Central_Park_Squirrel_Census_-_Squirrel_Data.csv') print(squirrel_data) gray_squirrels_count = len(squirrel_data[squirrel_data["Primary Fur Color"] == "Gray"]) red_squirrels_count = len(squirrel_data[squirrel_data["Primary Fur Color"] == "Cin...
nums = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] squared_nums = [num ** 2 for num in nums] print(squared_nums) numbers = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] even_nums = [num for num in numbers if num % 2 == 0] print(even_nums) with open('file1.txt') as file1: list1 = file1.read().split('\n') with open('file2.txt') as ...
import menu items = menu.MENU resources = menu.resources money = 0 def report(): print(f"Water: {resources['water']}\nMilk: {resources['milk']}\nCoffee: {resources['coffee']}\nMoney: {money}") def is_sufficient(req): return req['water'] <= resources['water'] and req['milk'] <= resources['milk'] and req['co...
import math def five_percent(num): return math.ceil(num + (num * 0.05)) while True: print(five_percent(int(input("num: "))))
def multiply_by_2(a_dictionary): new_dict = {} keys = a_dictionary.keys() for key in keys: new_dict.update({key: a_dictionary.get(key) * 2}) return (new_dict)
'''Prints a string, adding two newlines after each of the following: '.', '?', and ':' Text must be a string''' def text_indentation(text): '''Usage: text_indentation(text)''' if not isinstance(text, str): raise TypeError('text must be a string') flag = 0 for char in text: if flag is ...
'''Adds two integers If floats are sent, casts to int before adding''' def add_integer(a, b=98): '''Usage: add_integer(a, b=98)''' if (a == float("inf") or (not isinstance(a, int) and not isinstance(a, float)) or a != a): raise TypeError('a must be an integer') el...
def islower(a): a = ord(a) if a > 96: return(a - (ord("a") - ord("A"))) else: return(a) def uppercase(s1): s2 = list(s1) for i in range(len(s2)): check = islower(s2[i]) s2[i] = chr(check) print("{:s}".format(s2[i]), end="") print("")
'''Defines a function that appends a string to a text file (UTF8) and returns the number of characters written:''' def append_write(filename="", text=""): '''Usage: append_write(filename="", text="")''' with open(filename, "a") as f: f.write(text) f.close() return len(text)
'''Defines a function that inserts a line of text to a file, after each line containing a specific string''' def append_after(filename="", search_string="", new_string=""): '''Usage: append_after(filename="", search_string="", new_string="")''' with open(filename, "r") as f: res = [] s = f.r...
'''Square class''' class Square: '''Defines a square class with logical operators available based on area, as well as size and area''' __size = 0 def area(self): '''area getter''' return (self.__size ** 2) def __init__(self, size=0): '''Initializes size''' self.__si...
Square = __import__('6-square').Square my_square_1 = Square(3) my_square_1.my_print() print("--") my_square_2 = Square(3, (1, 1)) my_square_2.my_print() print("--") my_square_3 = Square(3, (3, 0)) my_square_3.my_print() print("--") try: my_square_4 = Square(0, (0)) my_square_4.my_print() except Exception...
import os import tempfile import shutil import requests import urllib from urlparse import urlsplit import logging logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) def check_create_folder(folder_name): """ Small utility function to check if a folder already exists, and create...
class BinaryTree(object): def __init__(self, root_value): self.root = root_value self.leftchild = None self.rightchild = None def insert_left(self, left_value): if self.leftchild == None : self.leftchild = BinaryTree(left_value) else: le...
def bubble(arr): for j in range(len(arr)): for i in range(len(arr)-1): first = arr[i] second = arr[i+1] if first > second: temp = arr[i+1] arr[i+1] = arr[i] arr[i] = temp print(arr) bubble([9, 4, 3, ...
class Stack(object): def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def size(self): return len(self.items) def pop(self): return self.items.pop() def push(self, item): self.items.append(item) class Q...
import socket import sys import time s = socket.socket() host = socket.gethostname() print("Server will start on host:", host) port = 8080 s.bind((host,port)) print("") print("Server done binding to host and port successfully") print("") print("Server is waiting for incoming connections") print("") ...
"""def binarysearch(slist, value, last_index): length = len(slist) if(length==0): return -1 if(length==1): return 0 if slist[0]==value else -1 index = length/2 if(slist[index]==value): return last_index elif(value<slist[index]): if(length%2==0): last_...
import copy class Tile: def __init__(self , type : int, col : int, row : int): self.type=type self.col=col self.row=row def __str__(self): return str(self.type) def coord(self): return("col: " + str(self.col) + " row: " + str(self.row)) ...
name = "Ganesh Salunkhe" newString = name.replace('a', 'A') print(newString)
import os import shutil from os import path w = open("getPathFileone.txt", "w+") w.close() if(path.exists("getPathFileone.txt")): src = path.realpath("getPathFileone.txt"); haid, tail = path.split(src) print ("Path :", haid) print ("File :", tail)
file = open("ReadFile.txt" ,"w+") file.write("Ganesh Salunkhe") file = open("ReadFile.txt" ,"r") re= file.read() print(re)
def sampleSTRForLoop(): str = ["Apple", "Banana", "Grapes", "Mango", "Chiku"] for x in range(2, 5): print(str[x]) sampleSTRForLoop()
import os.path from os import path w = open("file.txt","w+") m = open("D:\PythonWorkPlace\samplefile.txt","w+") print("file exist:" + str(path.exists("guru99.txt"))) print("file exists:" + str(path.exists("file.txt"))) print("Directory exists:" + str(path.exists("D:\PythonWorkPlace"))) print("Directory exists:" + s...
def sampleForLoop(): number = [2, 12, 14, 28, 9, 27, 35, 44, 78] for x in range(2, 7): print(number[x]) if (number[x]==9): break sampleForLoop()
a = (5, 3) b = (5, 4) if (a > b): print("a is bigger") else: print("b is bigger")
def SampleIfElse(): num, num1 = 25, 35 st = (num, "Is less than num1") if (num < num1) else print(num, "Is greater than num1") print(st) SampleIfElse()
a = (0, 5) b = (1, 4) if (a > b): print("a is bigger") else: print("b is bigger")
""" 1. Python calls an instance's __call__() when it's used as a decorator 2. __call__()'s return value is used as the new function 3. Creates groups of callables that you can dynamically control as a group """ class Trace: def __init__(self): self.enabled = True def __call__(self, f): def wr...
import random from functools import wraps import time import matplotlib.pyplot as plt import matplotlib as mat def list_generator(size, low=1, high=10000): """generates a list of random numbers from 1 to 10,000""" print("\n\nGenerating list of size {}".format(size)) randomlist = [random...
number=int(input("Enter The Number : ")) count = 0 while number > 0: count=count+1 number = number//10 print ("Number of digits in the given number is ", count)
i = 0 while i < 11 : n = input("Pls, Enter ur Name :") grade = int(input("whats ur Grade in %")) if grade>=85 and grade<=100: print(f" Name of Student : {n} Grade is {grade} % Rate : Excellent") Rate = "Excellent" elif grade>=70 and grade<85: print(f" Name of Student : ...
''' Implementation of stack in python ''' class stack: st = list() def push(self, i): self.st.append(i) print("pushed : ", i) def pop(self): if(self.st): print("popped : ", self.st.pop()) else: print("nothing to pop!!") def main(): ll = stack()...
def higher_lower(x): if x<24: return("higher") elif x>24: return("lower") else: return("correct u dumb") print(higher_lower(24)) def categorize(x): if x<20: return("low") elif x>=20 and x<36: return("medium") else: return("high") d...
import math a = 3.14 y = math.pi y = round(y, 2) b = math.pi b = pow(b, 10) leo = "tonto" leo = leo.replace("tonto", "wea") print("weon " + str(a) + " qlao " + str(y) + " la " + str(b) + " " + str(leo)) import math import math def distance(x,y): euclidian = math.sqrt(((12.5 - x)**2) + (-7.3 - y)**2) ...
class Stack: def __init__(self): self.lst = [] def is_empty(self): return len(self.lst) == 0 def top(self): if self.is_empty() is False: return self.lst[-1] else: return None def append(self, value): self.lst.append(value) def pop(s...
from codewars.linkedlist import LinkedList def union(list1, list2): list3 = LinkedList() node = list1.get_head() while node is not None: list3.insert_at_tail(node.data) node = node.next_element node = list2.get_head() while node is not None: list3.insert_at_tail(node.data...
from codewars.linkelistalt import LinkedList, Node, rotate_list def test_print_all(): linked_list = LinkedList() for i in range(1, 6, 1): linked_list.add(Node(i)) linked_list.print_all() rotate_list(linked_list, 2) linked_list.print_all() def test_print_all_2(): linked_list = LinkedL...
import numpy as np import pandas as pd from .base_random_cell import BaseRandomCellTransform class FeatureDropout(BaseRandomCellTransform): """ A batch transformation for randomly dropping values in the data to some pre-defined values **Parameters** - **n_probs** - a *list*, *tuple* or a *one dimension...
""" Author: Abas Farah This is code for graphs.py This file has some prebuilt graphs using the: --> Adjecency List --> Adjecency Matrix --> Adjecency List with edge weights --> Object oriented graph with edge weights """ import sys import os dirpath = os.path.dirname(os.p...
import math def vector_subtract(v, w): """subtracts two vectors componentwise""" return [v_i - w_i for v_i, w_i in zip(v,w)] def dot(v, w): """v_1 * w_1 + ... + v_n * w_n""" return sum(v_i * w_i for v_i, w_i in zip(v, w)) def sum_of_squares(v): """v_1 * v_1 + ... + v_n * v_n""" return dot...
import flickrapi def session(filename): """Open an instance of the Flickr API given an API key.""" with open(filename) as f: api_keys = f.readlines() api_key = api_keys[0].rstrip() api_secret = api_keys[1].rstrip() session = flickrapi.FlickrAPI(api_key, api_secret) retu...
num1 = float(input(" ENTER NUMBER 1: ")) num2 = float(input(" ENTER NUMBER 2: ")) num3 = float(input(" ENTER NUMBER 3: ")) if num1>num2 and num1>num3: print(" NUMBER 1 is the greatest") elif num2>num1 and num2>num3: print(" NUMBER 2 is the greatest") else: print(" NUMBER 3 is the gr...
num = int(input(" ENTER NUMBER: ")) print(" The factors of",num,"are: ") def factors(num): if num == 0: print(" Zero has no factors") else: for loop in range(1,num+1): if num % loop == 0: factor = loop print(factor) factors(num)
a=0 b=1 a=int(input("Enter a: ")) print(" Value of a is: ",a) b=int(input("Enter b: ")) print(" Value of b is: ",b) a,b=b,a print(" \n Now Value of a is:",a) print(" and Now Value of b is:",b)
number=float(input(" Enter the variable u wanna check: ")) if number < 0: print("THIS IS A NEGATIVE NUMBER") elif number == 0: print(" THE NUMBER IS ZERO") else: print(" THIS IS A POSITIVE NUMBER") if number%2 == 0: print("The number %i is even number" %number) else...
class Solution: def canJump(self, nums: List[int]) -> bool: if nums[0]>= len(nums)-1: return True idx = len(nums)-2 dest = len(nums)-1 while idx >= 0: if nums[idx] >= dest-idx: dest = idx if dest == 0: ...
from math import factorial error = float(input()) res = 0 i = 0 while True: res += 1/factorial(i) if 1/factorial(i+1) <= error: res += 1/factorial(i+1) break else: i += 1 print(f'{res:.6f}')
""" timeout def fib(n): if n == 1 or n == 2: return 1 return fib(n - 1) + fib(n - 2) """ def fib(n): pre , cur = 0, 1 for _ in range(1, n): pre , cur = cur, pre + cur return cur n = int(input()) if n < 1: print('Invalid.') else: for i in range(1, n+1): print(f'{fib...
n = int(input()) count = 0 sum = 0 for i in range(n): dic = eval(input()) for item in dic: path = dic[item] for key in path: count += 1 sum += path[key] print(n, count, sum)
str = input().strip() chr_remove = input().strip() str = str.replace(chr_remove.upper(), '').replace(chr_remove.lower(), '') print(f'result: {str}')
lst1 = list(input().split())[1:] lst2 = list(input().split())[1:] res = [] for num in lst1: if num not in lst2 and num not in res: res.append(num) for num in lst2: if num not in lst1 and num not in res: res.append(num) print(' '.join(res))
from math import factorial n = int(input()) res = 0 for i in range(1,n+1,2): res += factorial(i) print(f'n={n},s={res}')
shop_list = ['apple', 'mango','banana'] print('I have',len(shop_list),'items') print('These items are:', end=' ' ) for items in shop_list: print(items, end=' ') print('items', shop_list) print('adding rice') shop_list.append('rice') print('updated: ',shop_list) print('Sorting list') shop_list.sort() print('...
number = 19 guess = int(input('Enter an int:')) if guess == number: print('Spot on') elif guess < number: print('A little higher') else: print('A öittle lower') print('Done')
from keras.datasets import boston_housing from keras.models import Sequential from keras.layers import Activation, Dense from keras import optimizers (X_train, y_train), (X_test, y_test) = boston_housing.load_data() model = Sequential() model.add(Dense(10, input_shape = (13,))) model.add(Activation('si...
def prime_num_or_not(n): if n>1: for i in range(2,n): if (n%i)==0: print('given number is not prime') print(i,"times",n//i,"is",n) break else: print('given number is prime') else: print('given number is not prime') ...
def reverse_letters(string): if len(string)==1: return string return reverse_letters(string[1:]) + (string[0]) string='lohit badiger' print(reverse_letters(string)) print('----------------------------') def reverse_letter2(string): string = "".join(reversed(string)) print(string) s...
class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: List[int] """ allnumsxor = nums[0] """ this will basically give us the XOR of those two target nums which appear just once in nums note that for 2 ...