text
stringlengths
5
121k
""" Created on Fri Nov 22 11:35:20 2019 @author: 10649929 """ import nltk from nltk.stem import PorterStemmer from nltk.corpus import stopwords paragraph="""I have three visions for India. In 3000 years of our history people from all over the world have come and invaded us, cap...
person_detail = { 'first_name': 'fortunes', 'last_name': 'onyekwere', 'age': 21 } person_details2 = dict(first_name = 'fortunes', last_name='onyekwere') print(person_detail) print(person_detail['first_name']) person_detail['phone_number'] = '+2347067162698' print(person_detail) print(person_de...
students = ['fortunes', 'abdul', 'obinaka', 'amos', 'ibrahim', 'zaniab'] for student in students: print(f'i am: {student}') for student in students: if student == 'odinaka': break print(f'the student is: {student}') for student in students: if student == 'odinaka': continue ...
def main(): import random, string password_length = int(input("How many characters would you like your password to have? ")) password = [] password_characters = string.ascii_lowercase + string.ascii_uppercase + string.digits for x in range (passwo...
start = int(input("Enter a integer to start the madness: ")) loop = 1 print(start) while start > 1: if (start % 2) == 0: start = int(start / 2) else: start = start * 3 + 1 loop+=1 print(start) print("It was in total", loop, "loops it it ends!")
from abc import ABC, abstractmethod from PickleMaker import * from shelve import * class AbstractSerializerFactory(ABC): """ The Abstract Factory interface declares a set of methods that return different abstract products. These products are called a family and are related by a hi...
def rev_words_in_sentence(statement): stm=statement.split() l=[] for s in stm: l.append(s[::-1]) final_l=' '.join(l) return final_l if __name__ == '__main__': m=input("Enter sentence for processing: ") print(rev_words_in_sentence(m))
def reverse_sentence(statement): stm=statement.split() rev_stm=stm[::-1] rev_stm=' '.join(rev_stm) return rev_stm if __name__ == '__main__': m=input("Enter the sentence to be reversed: ") print(reverse_sentence(m))
def encrypt(text): result = [] for letter in text: l = ord(letter) - 42069 result.append(l) print("This is your encrypted message: ") for numbers in result: print(numbers, end='') print("", end='') decrypt(result) def decrypt(result): end_string = "" for n...
class Stack(object): """ Implementation of the stack structure. """ def __init__(self): self._items = [] def clean(self): """ Removes all items. """ self._items = [] def push(self, item): """ Adds given item at the top of the stack. ...
""" Created on Thu Feb 2 04:03:21 2017 @author: Andrew """ ans = 0 neg_flag = False x = float(input("Enter an integer: ")) if x < 0: neg_flag = True while ans**2 < x: ans = ans + 1 if ans**2 != x: ans -= 1 while ans**2 < x: ans = ans + .1 if ans**2 != x: ans -= .1 while ans**2 < x: ...
""" Created on Sat Apr 1 09:22:30 2017 @author: Andrew """ class Friends: def __init__(self, connections): ''' input: a tuple of sets with two items in each set returns: nothing ''' self.connections = connections def getConnections(se...
""" Created on Wed Feb 1 21:15:27 2017 @author: Andrew """ s = "zyxwvutsrqponmlkjihgfedcba" if (len(s) != 1): alpha = "abcdefghijklmnopqrstuvwxyz" count = 0 alp1 = 0 alp2 = 0 begin = 0 end = 0 ans = "-" for letter in range(len(s)-1): if (len(s) - c...
""" Created on Wed Mar 22 01:31:21 2017 @author: Andrew """ class item(object): def __init__(self, name, value, weight): self.name = name self.value = value self.weight = weight def getName(self): return self.name def getValue(self): retu...
""" Created on Mon May 15 08:45:03 2017 @author: Andrew """ from tkinter import * top = Tk() L1 = Label(top, text = "Tax Calculator") L1.pack(side = TOP) L2 = Label(top, text = "Tax rate:") L2.pack(side = LEFT) E1 = Entry(top, bd = 4) E1.pack(side = RIGHT) L4 = Label(top, text = "") L4.pack(side = TOP) L3 = Label(t...
""" Created on Thu Mar 30 11:13:15 2017 @author: Andrew """ def yieldAllCombos(items): """ Generates all combinations of N items into two bags, whereby each item is in one or zero bags. Yields a tuple, (bag1, bag2), where each bag is represented as a list of which item(s) are in each b...
""" Created on Fri Feb 3 04:43:48 2017 @author: Andrew """ """ Created on Fri Feb 3 03:31:42 2017 @author: Andrew """ balance = 4773 annualInterestRate = .2 monthlyInterestRate = annualInterestRate / 12 monthlyUnpaidBalance = balance updatedBalanceEachMonth = monthlyUnpaidBalance + (monthlyInterestRate ...
import smtplib from email.message import EmailMessage email = EmailMessage() email['from'] = 'Ankur Bhalla' email['to'] = '<enter receiver email>' email['subject'] = 'You won 1,000,000 dollars!' email.set_content('I am a Python Master!') with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp: smtp.ehl...
''' Create a Factorial To solve this problem: 1. Create a function that will find the factorial for a value using a recursive function. Factorials are calculated as such 3! = 3 * 2 * 1 2. Expected Output Factorial of 4 = 24 Factorial at its recursive form is: X! = X * (X-1)! ''' def factorial(n): if n==...
''' To solve this problem: Don't use the input function in this code 1. Assign a value of 5 to the variable tree_height 2. Print a tree like you saw in the video with 4 rows and a stump on the bottom TIP 1 You should use a while loop and 3 for loops. TIP 2 I know that this is the number of spaces and hashes for the tre...
import csv import datetime import requests FILE_URL="http://marga.com.ar/employees-with-date.csv" def get_start_date(): """Interactively get the start date to query for.""" print() print('Getting the first start date to query for.') print() print('The date must be greater than Jan 1st, 2018') ...
import unittest import universal_translator class UniversalTranslatorTest(unittest.TestCase): '''Raises file not found error if the given file route is empty''' def test_empty_file_route(self): universe = universal_translator.UnitsTranslator('') with self.assertRaises(FileNotFoundError): ...
import os import sqlite3 DB_FILEPATH = os.path.join(os.path.dirname(__file__), "northwind_small.sqlite3") connection = sqlite3.connect(DB_FILEPATH) cursor = connection.cursor() query = """ SELECT ProductName, UnitPrice FROM Product ORDER by UnitPrice DESC LIMIT 10; """ result = cursor.execute(query).fetchall()...
""" Step 2 : Data aggregation: aggregate data to generate text corpus: This will clean the raw data that was gathered from Reddit - - convert data to format that can be directly consumed by Dataframes, """ import pandas as pd import os from .config import ( AGG_BY_SUB, COMMENTS_COLS, REPLIES_COLS, ) class...
def longestWordLength(string): length=0 for word in string.split(): if(len(word)>length): length=len(word) return length string="I am an intern at geeksforgeeks" print(longestWordLength(string))
''' this is a multiline comment ordocstring (used to define a function purpose) can be single or double quotes ''' """ Variable Rules: - Variable names are case sensitive (name and name are different variables) - Must start with a letter or an underscore -can have number but can not start with one """ ''' Variabl...
import math class ellipse_default: 'Creates a default ellipse class to set default parameters, find area and circumference' def __init__ (self,xcoord = 0,ycoord = 0, a = 0, b = 0): 'Creates an ellipse with default parameters of (x,y) = (0,0) and (a,b) = (0,0)' self.x = (xcoord) ...
import time print("Welcome to Kala's calculator") while True: print("\nHere are the options") options = input("please enter 1 for addition, 2 for subtraction, 3 for division and 4 for multiplacation") if options == "1" : time.sleep(2) print("\n you have chosen addition") num1...
from functools import reduce def append(list1, list2): return list1+list2 def concat(lists): result = [] for list in lists: result += list return result def filter(function, list): return [v for v in list if function(v)] def length(list): n = 0 for _ in list: n += 1 ...
def is_number(s): try: int(s) return True except ValueError: return False def isperfectNumber(n): a = 1 b = n s = 0 while a < b: if n % a ==0: s += a + b a += 1 b = n/a if a ==b and a*b == n: ...
class Money: def __init__(self, name= None, symbol= None ): self.kind = '' self.name = name self.symbol = symbol def __str__(self) -> str: return f'The {self.name} is {self.kind} money and has symbol {self.symbol}' def money_type(self): return self.kind de...
a,b,c=input().split('-') if b=='01': print("January") elif b=='02': print("Febrary") elif b=='03': print("March") elif b=='04': print("April") elif b=='05': print("May") elif b=='06': print("June") elif b=='07': print("July") elif b=='08': print("August") elif b=='09': print("Septemb...
def main(): global grid_size global row_sign global col_sign row_sign = "-" col_sign = "|" print("Quiz 4") row_num = int(input("Numbers of rows:")) col_num = int(input("Numbers of colum:")) grid_size = int(input("Grid size:")) row_sign = row_sign*grid_size for i in rang...
class AddStu(): def __init__(self, student_dict): self.student_dict = student_dict def execute(self): try: print("新增學生姓名和分數") name = str(input(" Please input a student's name: ")) subject = "" score = 0 while subject != "exit": ...
from DB.DBConnection import DBConnection class StudentInfoTable: def insert_a_student(self, name): command = "INSERT INTO student_info (name) VALUES ('{}');".format(name) with DBConnection() as connection: cursor = connection.cursor() cursor.execute(command) ...
import pygame from program import Program WIDTH=1024 HEIGHT=768 GREY=(210, 210 ,210) FPS=60 BACKGROUND_COLOR=GREY TITLE='ROUTING NETWORK SOFTWARE' pygame.init() def main(): font = pygame.font.Font(None, 32) pygame.display.set_caption(TITLE) screen = pygame.display.set_mode((WID...
def two_dimensional_booleans(super_list, use_and): results=[] for a_list in super_list: if not use_and: results.append(True in a_list) else: results.append(not False in a_list) return results bool_superlist = [[True, True,...
def stars(movies, tvshows): newdict={} for tupl in movies.items(): (movie_name, actor_list)=tupl for actor in actor_list: if actor not in newdict: newdict[actor]=[] newdict[actor].append(movie_name) for tupl in tvshows.items(): (tvshow_name, actor_list)=tupl for actor in ...
def fib(n): if n == 1 or n == 2: return 1 else: return fib(n - 1) + fib(n - 2) print("fib(5) is", fib(3)) print("fib(10) is", fib(10)) print() def fib(n): if n == 1 or n == ...
def reader(filename): input_file=open(filename, "r") result=[] for line in input_file.readlines(): list_of_fields = line.strip().split(" ") number=int(list_of_fields[0]) assignment=str(list_of_fields[1]) score=int(list_of_fields[...
import math def triangle_area(b,h): a = (1/2) * b * h return a def circle_area(r): a = math.pi * r**2 return a def parallelogram_area(b,h): a = b * h return a def trapezoid_area(c,b,h): a = ((c + b) / 2) * h return a def rect_prism_volume(w,h,l): v = w *...
import tkinter as tk import calendar as cl class MainHeader(tk.Frame): def __init__(self, parent, controller, month, year, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) header_font = ("Helvetica", 20, "bold") self.header_lbl = tk.Label( s...
from random import randint from time import ctime from time import sleep import queue import threading class MyTask(object): def __init__(self, name): self.name = name self._work_time = randint(1, 5) def work(self): print("Task %s is start : %s, sleep tim...
import turtle import os wind = turtle.Screen() t = turtle.Turtle() for loop in range(4): t.forward(100) t.right(90) t.home() yy = 10 for loop in range(100): t.dot ( yy,"cyan") yy=yy+5 t.home() t.write("Finished - click window to close") wind.exitonclick ( )
from library.modulos import num_perfecto def principal(): numero = int(input("Digite un numero: ")) if num_perfecto(numero): print("Es perfecto") else: print("No es perfecto") if __name__ == "__main__": principal()
import re import datetime class Reader: fileName = "" def __init__(self, fileName): self.fileName = fileName def convertTeamName(self, name): """convert string to upper case and strip spaces Take the given team name remove whitespace and convert to uppercase """ ...
import numpy as np import matplotlib.pyplot as plt m = 100 X = 6 * np.random.rand(m, 1) - 3 y = 2 + X + 0.5 * X**2 + np.random.randn(m, 1) plt.plot(X, y, 'r.') plt.show() from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression poly_features = PolynomialFeatures(degre...
import time import brickpi3 BP = brickpi3.BrickPi3() BP.set_sensor_type(BP.PORT_1, BP.SENSOR_TYPE.TOUCH) try: print("Press touch sensor on port 1 to run motors") value = 0 while not value: try: value = BP.get_sensor(BP.PORT_1) except brickpi3.SensorError: ...
class RandomListNode: def __init__(self, x): self.label = x self.next = None self.random = None class Solution: def Clone(self, pHead): self.cloneNodes(pHead) self.connectRandomNodes(pHead) self.reConnectNodes(pHead) def cloneNodes(self,pHead): ...
class Car(): def __init__(self, brand, model, year=2000): self.brand = brand self.model = model self.year = year self.velocity = 0 def presentCar(self): message = "{} {} created in {}".format(self.brand, self.model, self.year) if 2019-self.year >= 20: ...
""" Created on Thu Jan 3 22:23:25 2019 @author: biam05 """ dec = int(input('Decimal number (base 10):')) final = '' while dec > 0: final += str(dec % 2) dec = dec // 2 print(final[::-1])
""" Created on Fri Oct 26 14:42:58 2018 @author: biam05 """ n1 = int(input("Size 1: ")) n2 = int(input("Size 2: ")) n3 = int(input("Size 3: ")) if n1 <= (n2 + n3) or n2 <= (n1 + n3) or n3 <= (n1 + n2) or n1 < 0 or n2 < 0 or n3 < 0: result = str("Not a triangle") else: if n1 == n2 and n2 == n3: resul...
""" Created on Thu Jan 3 21:46:03 2019 @author: biam05 """ tS = float(input('Swimming time:')) tC = float(input('Cycling time:')) tR = float(input('Running time:')) if tS + tC + tR >= 4: print('Time') else: if 1.5 / tS < 2: print('Swimming') else: if 40/tC < 20: print('Cycli...
""" Created on Sun Dec 23 16:26:15 2018 @author: biam05 """ def parse(filename): from ast import literal_eval as l_eval file = open(filename, 'r') content = file.read() content = content.split() contstr = '' for i in range(len(content)): if content[i][0] != '(': content[i]...
""" Created on Wed Oct 17 21:46:12 2018 @author: biam05 """ def triangle_form(): result = "Not yet implemented" x = int(input(" ")) y = int(input(" ")) z = int(input(" ")) if ((x + y) <= z) or ((x + z) <= y) or ((y + z) <= x): result = "Not a triangle" else: ...
""" Created on Thu Oct 25 17:12:31 2018 @author: biam05 """ n = int(input("n = ")) nn = str(n) + str(n) nnn = str(n) + str(n) + str(n) expression = n + int(nn) + int(nnn) print("n + nn + nnn =", expression)
""" Created on Wed Oct 24 11:47:09 2018 @author: biam05 """ def sum_numbers(n): """ returns the sum of all positive integers up to and including n """ if n >= 0: result = n for i in range(n): result += i else: result = 0 return result ...
""" Created on Tue Dec 11 10:44:03 2018 @author: biam05 """ def override(l1, l2): return sorted(l2 + [l1[i] for i in range(len(l1)) if l1[i][0] not in [l2[k][0] for k in range(len(l2))]], key = lambda x: x[0])
""" Created on Thu Jan 3 21:52:38 2019 @author: biam05 """ dec = int(input('Decimal number (base 10):')) result = '' while dec > 0: result += str(dec%8) dec = dec//8 print(result[::-1])
""" Created on Fri Oct 26 14:52:15 2018 @author: biam05 """ n1 = int(input("Number 1: ")) n2 = int(input("Number 2: ")) x = n1 y = n2 i = 0 result = 0 while y > 0: y = y % 10 result += (y*(10**(i))) y = n2 - result y = y / (10**(i)) i += 1 while x > 0: x = x % 10 result += (x*(10**(i))) ...
""" Created on Fri Oct 26 08:35:26 2018 @author: biam05 """ n = int(input("Integer: ")) divisor_list = [] for i in range (1, n+1): if (n % i) == 0: divisor_list.append(i) if len(divisor_list) == 2: result = True else: result = False print(result)
""" Created on Fri Jan 4 14:35:30 2019 @author: biam05 """ def evaluate(a, x): return sum(ai*x**e for e, ai in enumerate(a))
""" 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢? 注意:给定 n 是一个正整数。 示例 1: 输入: 2 输出: 2 解释: 有两种方法可以爬到楼顶。 1. 1 阶 + 1 阶 2. 2 阶 示例 2: 输入: 3 输出: 3 解释: 有三种方法可以爬到楼顶。 1. 1 阶 + 1 阶 + 1 阶 2. 1 阶 + 2 阶 3. 2 阶 + 1 阶 """ __author__ = 'Qiufeng' class Solution(object): def climbStairs(self, n): """ ...
import turtle wn = turtle.Screen() myTurtle = turtle.Turtle() myTurtle.shape("turtle") myTurtle.speed(1) myTurtle.pensize(8) myTurtle.color("blue") myTurtle.penup() myTurtle.backward(400) myTurtle.pendown() for i in range(3): myTurtle.forward(100) myTurtle.left(120) myTurtle.penup() myTurtle.forward(200) m...
space_number = int(input("Input a space number : ")) max_number = int(input("Input a max number : ")) i = 0 numbers = [] while i < max_number: print(f"At the top i is {i}") numbers.append(i) i = i + space_number print("Numbers now: ", numbers) print(f"At the bottom i is {i}") print("The ...
import numpy as np class Neuron: def __init__(self, nx): '''INTEGER & >1 CONDITION''' if type(nx) != int: raise TypeError('nx must be an integer') elif nx < 1: raise ValueError('nx must be a positive integer') else: self.__W = np.random.normal(siz...
def flatten(list, newList): for i in range(len(list)): if type(list[i]) is type([]): newList = flatten(list[i], newList) else: newList.append(list[i]) return(newList) def testSuite(): print(flatten([2,9,[2,1,13,2],8,[2,6]], [])) print(flatten([[9,[7,1,13,2],8],[7,6]], [])) print(flatten([[9,[7,1,13,2],...
import turtle wn = turtle.Screen() alex = turtle.Turtle() alex.write("Hello") alex.penup() alex.goto(200,200) alex.begin_fill() alex.circle(20) alex.end_fill() wn.mainloop()
def main(): strn = input("Enter text: ").lower() letterCount = {} for letter in strn: letterCount[letter] = letterCount.get(letter, 0) + 1 if letter == " ": del(letterCount[letter]) letterItems = list(letterCount.items()) letterItems.sort() print(letterItems) for i in range(len(letterItems)): tup = lett...
a = int(input("Enter A: ")) for x in range(1, 1000): for z in range (1,1000): y = a if x*x == y*y + z*z: if y < z < x: print(y,z,x)
def replace(s , old , new): "Replaces the old letter with the new one" word = s.split(old) newWord = new.join(word) print(newWord + "\n") return(newWord) def testSuite(): print("Mississippi","i","I") replace("Mississippi","i","I") s = "I love spom! Spom is my favorite food. Spom, spom, yum!" print(s,"om", ...
from tkinter import * from tkinter import Canvas from random import randint from tkinter.messagebox import* letrasUsadas=[] vidas=6 letrasAcertadas=0 ''' Verifica si la letra que se ingreso en el entry pertenece a la palabra del archivo plano y cuantas veces esta ''' def probarletra(): global vidas global let...
''' This script loads an image, creates ball objects and then bounces them around the display surface ''' import sys import random import math import pygame import pygame.gfxdraw from pygame.locals import * pygame.init() ''' DISPLAY SETUP -----------------------------------------------------------------...
import sys import random import math import pygame import pygame.gfxdraw from pygame.locals import * FUCHSIA = (255, 0, 255) PURPLE = (128, 0, 128) TEAL = (0, 128, 128) LIME = (0, 255, 0) GREEN = (0, 128, 0) OLIVE = (128, 128, 0) YELLOW = (255, 255, 0) ORANGE = (255, 165, 0) RED = (255, 0, 0) MA...
import numpy as np import matplotlib.pyplot as plt N = 100 def summation(f, n0, N): s = 0 for n in range(n0, N+1): s += f(n) return s def random_fourier(x, nmax): a = np.random.random(nmax+1)-0.5 b = np.random.random(nmax+1)-0.5 return summation(lambda n: a[n]*np.sin(n*np.pi*x) + b[n]...
balance = 4773 annualInterestRate = 0.2 monthlyInterestRate = annualInterestRate / 12 monthlyPayment = 0 updatedBalance = balance counter = 0 while updatedBalance > 0: monthlyPayment += 10 updatedBalance = balance month = 1 while month <= 12 and updatedBalance > 0: updatedBalance -= monthlyPayment ...
def factorial(a): result = 1 for i in range(1, a+1): result = result * i return result def e(n): e = 0.0 for i in range(0, n + 1): e = e + (1/factorial(i)) return e def f(x): return (x**3 - x - 2) EPSILON1 = 0.00001; EPSILON2 = 0.000001; a = 1 b = 2 ...
import csv import iso8601 from datetime import date try: file_name = 'city-temperature-data.csv' cities = set() data = {} with open(file_name, encoding='utf-8') as f: for line in f: line = line.strip() if line: line_elements = line.split(',') ...
""" Author: Danielle Larson Purpose: Output the reverse-complement of the given DNA strand """ import os import sys import argparse def get_args(): """get arguments""" parser = argparse.ArgumentParser( description='Reverse complement the DNA strand', formatter_class=argparse.ArgumentDefaults...
from server.route import Route from server.connection import Connection from server.util import Util util = Util() class Itinerary: def __init__(self,travelType,days,prefernce,state): self.travelType = travelType self.days = days self.prefernce = prefernce self.state...
import re def parse_all(string): regex = re.compile(r"((?P<add>\+\d+)|(?P<multiply>x\d+)|(?P<divide>\/\d+)|(?P<balance>\(\d+\))|(?P<subtract>\-\d+)|(?P<remove_digit>\<\<)|(?P<first_digit_to_second>(\d+)\=\>(\d+))|(?P<insert_number>\d))") match = regex.match(string) groups = match.groupdict() return [(a...
import numpy as np def fromAbove(numFloors,numElevators): rng = np.random.default_rng() elevatorPositions = rng.random((numElevators,2)) elevatorDistances = np.zeros(numElevators) for eIndex in range(numElevators): if elevatorPositions[eIndex,0] < 1/(numFloors-1): if elevatorPos...
import sys import csv import os import xlsxwriter file_name = os.path.splitext(os.path.basename(r"<file_location.csv>"))[0] + '.xlsx' wb = xlsxwriter.Workbook("<filename_you_choose.xlsx") ws = wb.add_worksheet(file_name) format1 = wb.add_format({'bg_color' : '#000033', 'bold': True, 'font_size' : 16, 'font_colo...
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: cur = None result = None while l1 is not None or l2 is not None: if l2 is None or (l1 is not None and l...
try: print('try...') x = 10 / 0 print('result:', x) except ZeroDivisionError as e: print("except:", e) finally: print("finally") print("End...") def MyError(ValueError): pass def foo(s): n = int(s) if n == 0: raise MyError("invalid value:%s" % s) return 10 / n foo("0")
d={'fey':'飞','ming':'明'} print(d.get('fey')) d['sun']='孙' print(d) for (k,v) in d.items(): print("key:",k,"value:",v) s=set(range(10)) print(s) l=['fey','ming','sun','n'] t=set(s.upper() for s in l if isinstance(s,str)) print(t) t.add('HA') from collections import Iterable print(isinstance((),Iterable)) print("abs...
class Solution: def isValidBST(self, root): return self.check(root, float("-inf"), float("inf")) def check(self, root, left, right): if not root: return True if not left < root.val < right: return False return self.check(root.left, le...
class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: i, j = 0, 0 while n > 0 and m > 0: if nums1[m - 1] > nums2[n - 1]: nums1[m + n - 1] = nums1[m - 1] m -= 1 else: nums1[m + n - 1] = nums...
import math import itertools def sieve(n): "Return all primes <= n." np1 = n + 1 s = list(range(np1)) s[1] = 0 sqrtn = int(round(n**0.5)) for i in xrange(2, sqrtn + 1): if s[i]: s[i*i: np1: i] = [0] * len(xrange(i*i, np1, i)) return filter(...
import math import itertools l = range(0,10) sums=0 for i in itertools.permutations(l,10): n=sum([i[j]*10**j for j in range(0,10)]) d234=int(n%(10**9) / 10**6) if d234%2!=0: continue; d234=int(n%(10**8) / 10**5) if d234%3!=0: continue; d234=int(n%(10**7) / 10**4) if d234...
""" Christian Huber CMS 380, Fall 2020 / Sprint 1 / MoreCalculations This script reads a text file's values and calculates and prints the mean, median, variance, and standard deviation. """ from math import sqrt import matplotlib matplotlib.use("Agg") from matplotlib import pyplot as plt def mean(x): ...
""" Christian Huber CMS 380, Fall 2020 / Sprint 3 / The Ticket Problem This script plots the results of a binomial process and the poisson pmf for a series of coin flips """ from random import random import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt from math import e from math...
from datetime import datetime thisYear = datetime.today().year age = int(input("올해 나이는 : ")) nextAge = 2050 - thisYear + age + 1 print("올해는 " + str(thisYear) + "년 입니다.") print("2050년은 %s살 이시네요" % str((2050 - thisYear + age)))
MAX_CAPACITY = 30 SMALL_DOG_MULTIPLIER = 10 MEDIUM_DOG_MULTIPLIER = 20 LARGE_DOG_MULTIPLIER = 30 def order_dog_food(small_dogs: int, medium_dogs: int, large_dogs: int, leftover_food: float) -> float: """ Calculates the amount of food to order for the month given the number of dogs in each size category, ...
i = 1 while i > 0: tri_number = 0 counter = 0 for j in range(1, i+1): tri_number = tri_number + j for k in range(1, tri_number + 1): if tri_number%k == 0: counter = counter + 1 print("triangle number ", tri_number, "counter =", counter, "i value", i) if c...
number = int(input("Enter the number ")) n = 1 prime_number_list = [] while len(prime_number_list) < number: counter = 0 for i in range(1, n+1): if n % i == 0: counter = counter + 1 if counter == 2: prime_number_list.append(n) n = n + 1 print("Length - ", len(prime_number_l...
from typing import Dict, Tuple, Iterable from itertools import product import string import random COLORS_AMOUNT = 256 MAX_COLORS_TO_COMPUTE = 36 ITERATION_NUM = 3 MAX_TEXT_LENGTH = round(MAX_COLORS_TO_COMPUTE / ITERATION_NUM) letters = list(string.ascii_lowercase) colors = tuple(range(COLORS_AMOUNT)) colors_per_l...
'''Nested lists''' carts = [['toothpaste', 'soap', 'toilet paper'], ['meat', 'fruit', 'cereal'], ['pencil', 'notebook', 'eraser']] person1 = ['toothpaste', 'soap', 'toilet paper'] person2 = ['meat', 'fruit', 'cereal'] person3 = ['pencil', 'notebook', 'eraser'] carts = [person1, person2, person3] print(carts) for va...
def aSillyFunctionShort(list): '''A function that will sort a list of dictionaries and group them alphabetically by brand then type''' return sorted(list, key=lambda k:(k['brand'], k['type']))
import os import argparse def validate_dir(directory): message = None if not os.path.exists(directory): message = 'Directory \"%s\" not found!' % directory else: if not os.path.isdir(directory): message = 'Enter path \"%s\" is not directory!' % directory return message de...