text
stringlengths
37
1.41M
number = float(input("Enter the number: ")) if number % 2 == 0: print("This is Even") elif number % 2 == 1: print("This is Odd") else: print("This is not Integer")
# Addition # print(10+5) We can directly give print statement like this. a = 10 b = 5 total = a + b print(total) # Subtraction # print(10-5) We can directly give print statement like this. a = 10 b = 5 total = a - b print(total) # Multiplication # print(10*5) We can directly give print stateme...
# Function Decorator # Example 1 def decor(fun): def inner(): print("Inner Function: Before enhancing Function") fun() print("Inner Function: After enhancing Function") return inner def num(): print("We will use this function") print("and will enhance this in decorator") result_fun = decor(nu...
str1 = "GeekyShows" str2 = "GeekyShows" str3 = "Python" str4 = "A" str5 = "B" result1 = str1 == str2 result2 = str1 == str3 result3 = str4 < str5 print(result1) print(result2) print(result3)
# Dictionary - copy() Method stu = {101: 'Rahul', 102: 'Raj', 103: 'Sonam' } print("Original Dict:") print(stu) print(id(stu)) print() new_stu = stu.copy() print("Copied Dict:") print(new_stu) print(id(new_stu))
# Example 1 def decor(fun): def inner(): a = fun() add = a + 5 return add return inner def num(): return 10 result_fun = decor(num) print(result_fun()) # Example 2 def decor(fun): def inner(): a = fun() add = a + 5 return add return inner @decor def num(): return 10 #r...
# Slicing 2D Array from numpy import * n = array([[10, 20, 30], [40, 50, 60], [70, 80, 90]]) print("Original Array") print(n) print("0th Row All Columns") # 0th Row All Columns a = n[0, :] for i in a: print(i) print("1st Row All Columns") # 1st Row All Columns b = n[1, :] for i in b: ...
# Comparing Two Dates from datetime import date d1 = date(2019, 6, 30) d2 = date(2010, 6, 30) print(d1==d2) print(d1>d2) print(d1<d2) print(d1!=d2)
# Dictionary - keys() Method stu = {101: 'Rahul', 102: 'Raj', 103: 'Sonam' } print("Original Dict:") print(stu) print() all_keys = stu.keys() print(all_keys) print() # converting into list keys_lst = list(all_keys) # printing converted list print(keys_lst) print() # accessing one element print(keys_lst[...
# Write once and use it as many time as you need # Defining Function one time def disp(): name = "GeekyShows" print("Welcome to", name) # Calling Function as many time as we need disp() disp() disp() #Divide Large task into many small task, helpful for debuging code # Seprate Function for Addition def ...
import pickle class Student: def __init__(self, name, roll, address): self.name = name self.roll = roll self.address = address def disp(self): print(f'Name: {self.name} Roll: {self.roll} Address: {self.address}') with open('student.dat', mode='wb') as f: stu1 = Student('Rahul', 101, 'Ranchi'...
print("****** isupper Function ******") name = "GEEKYSHOWS" str1 = name.isupper() print(name) print(str1) print("****** islower Function ******") name = "geekyshows" str1 = name.islower() print(name) print(str1) print("****** istitle Function ******") name = "Hello Geekyshows How Are You" str1 = name.is...
# Nested Tuple # Example 1 a = (10, 20, 30, (50, 60)) print(a) print(a[0]) print(a[1]) print(a[2]) print(a[3]) print(a[3][0]) print(a[3][1]) print() # Example 2 b = (50, 60) a = (10, 20, 30, b) print("A:",a) print("B:",b) print(a[0]) print(a[1]) print(a[2]) print(a[3]) print(a[3][0]) print(a[3][1])...
# Accessing Nested Dictionary using For loop a = {1: {'course': 'Python', 'fees':15000}, 2: {'course': 'JavaScript', 'fees': 10000 } } # Accessing ID print("ID:") for id in a: print(id) print() # Accessing each id keys for id in a: for k in a[id]: print(k) print() # Accessing each id keys --...
# Create Array Example 1 import array stu_roll = array.array('i', [101, 102, 103, 104, 105]) print(stu_roll[0]) print(stu_roll[1]) print(stu_roll[2]) print(stu_roll[3]) print(stu_roll[4]) # Create Array Example 2 import array as ar stu_roll = ar.array('i', [101, 102, 103, 104, 105]) print(stu_roll[0]) pri...
# Set Methods a = {'Rahul', 'Raj', 'Sonam', 'Rani'} b = {'Sumit', 'Rahul', 'Rani', 'Python', 'Java'} print("A:",a) print("B:",b) print() # intersection() Method # returns item which exists in both sets ism = a.intersection(b) print("Intersection:", ism) print() # union() Method # Returns all item ...
# extend () from array import * stu_roll = array('i', [101, 102, 103, 104, 105]) arr = array('i', [107, 108, 109]) n = len(stu_roll) i = 0 while(i<n): print(stu_roll[i]) i+=1 print("Array After Extend") stu_roll.extend(arr) n = len(stu_roll) i = 0 while(i<n): print(stu_roll[i]) i+=1
# Accessing 2D Array using for Loop from numpy import * a = array([[10, 20, 30, 40], [50, 60, 70, 80]]) for r in a: for c in r: print(c) print()
# Multitasking using Multiple Thread # Two Threads acting on same method from threading import * class Flight: def __init__(self, available_seat): self.available_seat = available_seat self.l = RLock() #print(self.l) def reserve(self, need_seat): self.l.acquire() self.l.acquire() #print(self...
# reshape ( ) Function # 1D to 2D from numpy import * a = array([1, 2, 3, 4, 5, 6]) b = reshape(a, (2, 3)) print(a) print(b) print() # 1D to 3D c = array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) d = reshape(c, (2, 3, 2)) print(c) print(d) print() #2D to 1D e = array([[1, 2, 3], [4, 5, 6]]) f = resha...
# Multiple Inheritance class Father: def __init__(self): super().__init__() # Calling Parent Class Constructor print("Father Class Constructor") def showF(self): print("Father Class Method") class Mother: def __init__(self): super().__init__() # Calling Parent Class Constructor print(...
# Dictionary - pop() Method stu = {101: 'Rahul', 102: 'Raj', 103: 'Sonam' } print("Original Dict:") print(stu) print(id(stu)) print() removed_value = stu.pop(102) #removed_value = stu.pop(106) # Key is not found so KeyError print("After Removing Dict:") print(stu) print(id(stu)) print("Removed Value:", rem...
# Assignment operators a = 10 b = 20 m = 15 y = a + b print(y) m += 10 print(m) # m-=10 # print(m) # m*=10 # print(m) # m/=10 # print(m) # m%=10 # print(m) # m**=2 # print(m) # m//=10 # print(m)
print("****** startswith Function ******") name = "Hi How are you" str1 = name.startswith('Hi') print(name) print(str1) print("****** endswith Function ******") name = "Thank you Bye" str1 = name.endswith('Bye') print(name) print(str1)
a = int(input("Enter Number Greater than 2: ")) if(a >= 2): print("Correct!! You have Entered:", a) else: print("Wrong!! You have Entered:", a)
# Nested Class class Army: # Outer Class def __init__(self): self.name='Rahul' self.gn = self.Gun() # Creating Inner Class Object def show(self): print("Name:", self.name) class Gun: # Inner Class def __init__ (self): self.name = 'AK47' self.capacity = '75 Rounds' self...
# Append Method a = [10, 20, -50, 21.3, 'Geekyshows'] print("Before Appending:") for element in a: print (element) # Appending an element a.append(100) print() print("After Appending") for element in a: print (element)
#uncoding: UTF-8 #Autor: Ana María López Soto #Descripción: El programa calcula la cantidad de insectos recolectados y el numero mayor de un conjunto. def calcularTotlalInsectos(): print("Bienvenido al programa que registra los insectos que recolectas ") total_insectos = 0 #Contador de insectos dias_transc...
def run_test(success): if success: print("✔️") else: print("❌") # return the sum of the 2 dimensional array # Iterate over indices rather than the items in the list # Hint: use the 'range' function to get indices, and name loop variable using i,j,k to signify that they are indices not values...
##hacker_Rank url= https://www.hackerrank.com/challenges/defaultdict-tutorial/problem from collections import defaultdict #creating the dictioanry that we will assign list in it d = defaultdict(list) #this will be used in the Group B which will tell us which key, would program # want to display lst=[] n, m...
from operacion_numeros.Intermedio import INTERMEDIO class Lista(INTERMEDIO): def __init__(self, lista=['P', 'O', 'O', '@', '1', ':', ')', '0', ' ', '-'], num=5): self.lista = lista self.num = num def presentalista(self): print('Recorrer lista') if len(self.lista) != 0: ...
''' Find the largest number that can be formed from the digits that's divisble by 3 ''' from array import array def sanitize(l): l.sort(reverse=True) return int("".join([str(i) for i in l if str(i).isdigit()])) def answer(l): # your code here ret = 0 flag_z = 0 flag_o = 0 count_z = 0 count_o = 0 count_t...
''' * Tell if a number is a Hamming number or not * Hamming numbers are formed like this: * 2^i x 3^j x 5^k ---- i,j,k > 0 ''' class Hamming: def __init__(self, number): self.number = number self.prime_numbers = [] def get_prime_numbers(self): self.prime_numbers.clear() copy_n...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # Recursive Solution # def isSymmetric(self, root: TreeNode) -> bool: # def _isSymmetric(left, right): # if left ...
if __name__ == "__main__": T = int(input()) for t in range(T): N = int(input()) left, right = 0, 0 power = 0 while N: now = N % 10 if now == 4: left += 2 * (10 ** power) right += 2 * (10 ** power) else: ...
# Bus-Online-Ticket-Booking-System A Bus Online Ticket Booking system, which uses GUI in python. Real time Online ticket booking system. '''Authors:- KAVAN DESAI Program:- BUS ONILE TICKET BOOKING SYSTEM ''' from tkinter import * import datetime from tkinter import Tk, mainloop,TOP from time import time import...
def celsius_to_kelvin(value_celsius): value_kelvin = 0.0 value_kelvin = value_celsius + 273.15 return value_kelvin def kelvin_to_celsius(value_kelvin): value_celsius = 0.0 value_celsius = value_kelvin - 273.15 return value_celsius value_c = 10.0 print(value_c, 'C is', celsius_to_kelvin(v...
F = int(input('Temperatur i Fahrenheit: ')) C = 5/9*(F - 32) print(f'Grader i Celcius: {C}')
Minuter = float(input('Samtals minuter per månad: ')) kostnadMin = float(input('Kostnad i kr per samtals minut: ')) pris = Minuter*kostnadMin if pris >= 300: pris = pris*0.9 print(f'Pris per månad efter 10% rabatt: {pris}kr') else: print(f'Pris per månad: {pris}kr')
import random import sqlite3 class BankingSystem: BIN = "400000" def __init__(self, currsor1, connection1): self.cursor = currsor1 self.connection = connection1 self.cursor.execute("SELECT count(*) FROM card;") self.id = int(self.cursor.fetchone()[0]) def create_account(sel...
import sys def print_last_f(): name_fp = open("name_file.txt", "a+") #f_names = name_fp.readlines() for f_name in name_fp: print f_name + "------------>\n" print f fp = open(f_name[:-1], "r") for content in fp: print content fp.close() def update_name_f(...
# CSCI3180 Principles of Programming Languages # # --- Declaration --- # # I declare that the assignment here submitted is original except for source # material explicitly acknowledged. I also acknowledge that I am aware of # University policy and regulations on honesty in academic work, and of the # disciplinary guide...
#!/usr/bin/env python ''' Condicionales [Python] Ejercicios de práctica --------------------------- Autor: Inove Coding School Version: 1.1 Descripcion: Programa creado para que practiquen los conocimietos adquiridos durante la semana ''' __author__ = "Inove Coding School" __email__ = "alumnos@inove.com...
days = "Mon Tue Wed Thu Fri Sat Sun" months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" print "Here are the days:", days print "Hera are the months:", months print """Thre's somthing going on here. With the three double-quotes. We'll be able to type as much as we like. Even 4 lines if we want, 0r 5, or 6."""
count = 0 while (count < 9): print 'The count is : ', count count += 1 print "end!"
""" Modifica tu programa de IMC Ejercicios04-05.py de la sesión anterior para que se ejecute hasta que el usuario lo desee. Por ejemplo, que después de imprimir el resultado de IMC y categoría, le pregunte al usuario si desea salir. """ while True: try: w = float(input("> Ingresa peso en kg: ")) as...
""" Este programa le pide al usuario que ingrese valores de peso en kilogramos y altura en metros para calcular el índice de masa corporal (IMC) y la categoría a la que pertenece la persona con esos valores de peso y altura. El programa sigue pidiéndole al usuario por nuevos valores hasta que presiona "S" para salir. A...
número = input("Ingresa número de horas: ") tarifa = input ("Ingresa tarifa por hora: ") pagar = float(número) pagar_2 = float(tarifa) print("Paga:", pagar * pagar_2) input()
import random take = int(input("Enter the maximim no here: ")) yguess = random.randint(1, take) for n in range(3): try: mguess = int(input("Enter your guess here: ")) except: print("Your guess is not a number!!!") mguess = int(input("Enter your guess here:")) if mguess ...
def iterative_factorial(n): # you substract 1 each time # 3, 3*2*1 # 1*2*3 result = 1 for i in range(1, n+1): ##O(n) result = result * 1 return result def recursive_factorial(n): # 3! 3*2*1 # 3! 3*2! #base case, stops the recursion if n == 1 : ...
def main(): print("Podaj liczbę ocen, które będą " "wchodzić w skład średniej") liczba_ocen = int(input()) suma = 0 for i in range(1, liczba_ocen+1): print("Podaj ocenę " + str(i)) ocena = float(input()) if ocena < 0: liczba_ocen = i - 1 break ...
import requests import json liga = input("Ingresa Liga: ") jornada = int(input("Ingresa jornada: ")) api =('https://api.football-data.org/v2/competitions/'+liga+'/matches') headers = { 'X-Auth-Token': '7a3b0df07f7a4c949dfe74e24f679d79', 'Accept-Encoding': '' } result = requests.get(api, headers=headers) #print(result....
import struct import sys PY3 = sys.version_info.major == 3 PY2 = sys.version_info.major == 2 # The int object in Python 2 does not expose the `to_bytes` method. if PY3: to_bytes = int.to_bytes from_bytes = int.from_bytes integer_types = (int,) force_str = str unicode = str elif PY2: int_f...
#Exemplo: conversor de temperatura de #Fahrenheit para Celsius F = float(input('Farenheit:')) C = 5 * (F-32)/9 print('Celcius: %2.1%f' %c)
#for == While inrustido texto = 'aeiou' k = 0 while k < len(texto): letra = texto[k] print(letra) k = k + 1
# ITEC 2905-Capstone # Boris Valle import random print('\nThis game is about you guessing the number that I am ' + 'that I am thinking. \n ') def main(): number_of_tries = 0 guess_the_number = randNumber() # for number_taken in roll(): number_of_tries += 1 #checks to see if the number is too high...
''' Created on Apr 10, 2019 @author: orcasweb ''' # put the number of days in each month in reg year and leap year in a list regYearMonthDays = [31,28,31,30,31,30,31,31,30,31,30,31] leapYearMonthDays = [31,29,31,30,31,30,31,31,30,31,30,31] # will use this to create a list of all days in a given month form 19...
''' Created on Apr 2, 2019 @author: orcasweb ''' from math import log10 import time ''' If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out i...
''' Created on Jan 26, 2019 @author: orcasweb ''' def sumNumDigits(numList): if(len(numList) == 1): return int(numList[0]) else: return int(numList[0]) + sumNumDigits(numList[1:]) staticNum = 1000 sumNum = sumNumDigits(list(str(2**staticNum))) print("2 to the power of 1000 is: "...
''' Created on May 18, 2020 @author: orcasweb ''' import itertools as itr circularPrimes = [] def isPrime(n): # make sure n is a positive integer n = abs(int(n)) # 0 and 1 are not primes if n < 2: return False # 2 is the only even prime number if ((n == 2) | (n =...
numero = 2 while numero <= 100: print (numero) numero += 2
#3. Write a Python program to append text to a file and display the text. from itertools import islice with open("text.txt", "a") as f: f.write("hello") f.write("everyone") print text.txt '''OUTPUT: heerapatilhelloeveryone '''
#9. Write a Python program to count the frequency of words in a file. from collections import Counter with open("text.txt") as f: print Counter(f.read().split()) '''OUTPUT: Counter({'\\n': 10, 'dfsdf': 2, '\\n,': 1, 'people': 1, 'fsdfgsdhf': 1, 'dfsdfs': 1, 'hi': 1, 'dfsdfsdf': 1, 'are': 1, 'how': 1, 'y...
#!/usr/bin/env python #-*-codong:utf-8-*- import pandas as pd aSer = pd.Series([1, 2.0, 'a']) print(aSer) bSer = pd.Series(['apple', 'peach', 'lemon'], index=[1,2,3]) print(bSer) print(bSer.index) print(bSer.values)
# loops = repeating a task n-times # for loop - uses start, stop, step for i in range (1, 5, 1): p = float(input('enter amount')) r = float(input('enter rate')) t = float(input('enter duration')) print('interest is ', p*r*t)
x = (int(input('Enter a number you multiply with: '))) i = 1 while (i <= 12): results = i*x print('{} * {} = {}' .format(i, x, results)) i = i + 1
import random import string class User: # Class that generates new instances of user user_list = [] # empty list def __init__(self, user_name, password, email): self.user_name = user_name self.password = password self.email = email def user_save(self): # saves user ...
def compile(alpha): print("Введите сдвиг") n = int(input()) print("Введите послание (eng)") s = input().strip() res = '' for c in s: res += alpha[(alpha.index(c) * n) % len(alpha)] print("Зашифрованное послание") print('Result: "' + res + '"') def decompile(alpha): print("В...
from numpy import * arr1 = array([2,4,6,8,7]) arr2 = array ([3,7,8,9,7]) arr3 = array([]) for i in range (5): x = arr1 + arr2 arr3.append(x) print(arr3) from array import * arr = array('i', []) n = int(input("Enter the length of the array")) for i in range(n): x = int(input("Enter the next value"))...
x= int(input("Enter the number of digits (minimum 2):")) y=0 z=1 print("Fibonacci Sequence:\n") print(y,",",z, end=", ") for i in range (2,x): next=y+z print(next, end=", ") y=z z=next
class Student: def __init__(self, m1, m2): self.m1 = m1 self.m2 = m2 def sum(self, a, b, c): s = 0 if a!= None and b!= None and c!= None: s = a + b + c elif a!= None and b!= None: s = a + b else: s=a return...
def fact(n): f=1 for i in range (1, n+1): f = f*i return f x = int(input("Enter a value to find it's factorial: ")) result = fact (x) print (result)
# -*- coding: utf-8 -*- """ Created on Sun Jul 19 17:08:55 2020 @author: Sudarshan,Shweta """ from emailValidation import email_validation from containsUrl import is_valid_url from getUserName import get_user_name from aadharValidation import is_valid_aadhar from dateExtraction import is_date from passwordValidation ...
numbers = [] def while_num (): global numbers for i in range(0, 6): print "At the top i is %d" % i numbers.append(i) print "Numbers now: ", numbers print "At the bottom i is %d" % i while_num() print "The numbers: " for num in numbers: print num
from sys import argv # stores the name of the file in variable filename #script, filename = argv # opens and creates an object of the file #txt = open(filename) print "Write the name of your file:" filename = raw_input('--> ') # prints the name of the file print "Here's your file %r:" % filename txt = open(filename...
import statistics import pandas as pd df=pd.read_csv("StudentsPerformance.csv") math = df["math score"].tolist() mean=sum(math)/len(math) sd=statistics.stdev(math) median=statistics.median(math) mode=statistics.mode(math) print("The mean is:", mean) print("the standard deviation is:", sd) print("The media...
# coding: utf-8 from queue import * try: from orderedset import OrderedSet except Exception as e: print(e) from threading import Lock class OrderedSetQueue(Queue): """ https://stackoverflow.com/questions/16506429/check-if-element-is-already-in-a-queue """ def _init(self, maxsize): ...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param A : head node of linked list # @return the head node in the linked list def subtract(self, a): if a==None: return -1 if a...
'''A Program to check whether to given trees are same.''' def isSameTree(self, a, b): if a is None and b is None: return 1 if (a is None and b is not None) or (a is not None and b is None): return 0 if a.val != b.val: return 0 return self.isSameTree(a....
'''A Program to invert a binary tree in-palce.''' def _invertTree(self,root): root.left,root.right=root.right,root.left if root.left != None: self._invertTree(root.left) if root.right != None: self._invertTree(root.right) def invertTree(self, root): ...
def missing_number(N_array): return int( (( (len(N_array)+2) * (len(N_array)+1))/2 ) - sum(N_array)) print(missing_number([1,2,4,5]))
# -*- coding: utf-8 -*- """ Created on Thu Jul 20 16:36:31 2017 @author: Lucas """ s = 2 n = [1,2] m = 3 while m <= 4000000: n.append(m) if n[-1] % 2 == 0: # if even number s = s + n[-1] m = n[-1] + n[-2] print(s)
# class products class Product: def __init__(self, item='', amount=0, price=0): self.item = item self.amount = amount self.price = price # products list produts_list = [ Product( 'leite', 2, 319 ) , Product( 'macarrão', 5, 220 ) , Product( 'batata', 5, 500 ) ...
def convertRunHr(runHr): hr_list = runHr.split('h') hr = int(hr_list[0]) min_list = hr_list[1].split('m') min = int(min_list[0]) totalHr = hr + min/60 return totalHr run_hour = input("Enter run hour of genset (eg. 30h20m): ") print(convertRunHr(run_hour))
# -*- coding: utf-8 -*- """ Convert number value to Thai read out Adapted from http://justmindthought.blogspot.com/2012/12/code-php.html """ import math __all__ = ["bahttext", "num_to_thaiword"] _POS_CALL = ["แสน", "หมื่น", "พัน", "ร้อย", "สิบ", ""] _NUM_CALL = ["", "หนึ่ง", "สอง", "สาม", "สี่", "ห้า", ...
def bubbleSort(a): n=len(a) for iterationNo in range(1,n+1): # Here we have n number of iterations. # At the end of each, we have the highest element at the end. for j in range(n-iterationNo): if a[j]>a[j+1]: a[j],a[j+1]=a[j+1],a[j] return a print(bubble...
def linearSearch(a, key): for element in a: if element == key: return 'Found' return 'Not Found' def binarySearch(a, key): n = len(a) if n == 1: if a[0] == key: return 'Found' return 'Not Found' mid = n // 2 if a[mid] == key: return 'Foun...
from random import randint minnum = int(input('Choose the smallest number I can pick ')) maxnum = int(input('Choose the biggest number I can pick ')) answer = randint(minnum, maxnum) userguess = int(input('What is the number I am thinking of from ' + str(minnum) + ' to ' + str(maxnum) + "...
## KlingonPoliteChange.py ## ## ## This program will compute the "polite change" a Klingon shop owner will give to his/her Klingon customers ## ## ## The lru is currently worth 90 monetary units (mu) ## The talon is currently worth 30 mu ## The darsek is currently worth 10 mu ## The shhhrok is currently worth ...
# -*- coding: utf-8 -*- """ Created on Wed Mar 3 14:01:52 2021 @author: Meem """ def remove(source, size, idx): for i in range(len(source)-1): if(i==idx): source[i]=0 for i in range(idx, len(source)-1): source[i]=source[i+1] source[size-1]=0 source=[10,20,30,40...
# -*- coding: utf-8 -*- """ Created on Wed Mar 3 13:15:39 2021 @author: Meem """ def shiftLeft(source, k): i=0 while(i<k): source[i]=source[i+k] i=i+1 i=len(source)-1 while(i>=k): source[i]=0 i=i-1 s=[10,20,30,40,50,60] shiftLeft(s, 3) print(s)
-*- coding: utf-8 -*- """ Created on Wed May 12 00:53:08 2021 @author: Meem """ def exponential(m,n): if n==0 or n==1: return m else: return m*exponential(m,n-1) pass print(exponential(3,2)) class Trace: def hMB(self,h): if (h==0): print("Stop: ",...
#!/usr/bin/env python # coding: utf-8 # # Board Game Review Prediction # conda install -c anaconda git # # git clone https://github.com/ThaWeatherman/scrapers.git # ### 1. Importing Libraries and Loading the Data # In[4]: import pandas import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_sele...
import random N = 10 lstNumbers = list(range(N)) random.shuffle(lstNumbers) print(lstNumbers) def performInsertionSort(lstNumbers): for itr1 in range(1, N): key = lstNumbers[itr1] itr2 = itr1 - 1 while itr2 >= 0 and lstNumbers[itr2] > key: lstNumbers[itr2 + 1] = lstNumbers[itr...
a = eval(input()) if a>0: print("Positive") if a == 0: print("Zero") if a<0: print("Negative")
""" [2015-05-18] Challenge #215 [Easy] Sad Cycles https://www.reddit.com/r/dailyprogrammer/comments/36cyxf/20150518_challenge_215_easy_sad_cycles/ Given a base b and a starting number n, produce the first x terms in the b-sad cycle for n. The next number in a sad cycle is defined as taking the current number, and add u...
#!/usr/bin/python3 import argparse import collections import csv import glob import json import math import os import pandas import re import requests import string import sys import urllib from calendar import monthrange as cal def winner(t1, precip1, t2, precip2): win = '#' W = -1 L = -1 if precip1 >...
with open("name") as file: for line in file: print(line.upper()) #creates newlines at the end, print adds a new one #to avoid above with open("name") as file: for line in file: print(line.strip().upper()) #to get file content in a list-like structure file = open("name") lines = file.readlines() #read all ...
"""Implement an Anagram Program From 2.8 of Programming Pearls (2nd ed.) by Jon Bentley """ from typing import Iterator, Tuple, List, Dict from pathlib import Path from collections import defaultdict from operator import itemgetter import argparse def load_words() -> Iterator[str]: """Iterate through words that...
#bruce diaz #program will ask user for two inputs and then see if it is less than or greater than 10. def evaluateInput1(): input1 = input("Enter your first value") input2 = input("Enter your second value") if input1 + input2 > 10: print("your sum is greater than 10") if input1 + input...