text
stringlengths
37
1.41M
totalMinuter = int(input("mata in antal minuter:")) timmar = totalMinuter // 60 minuter = totalMinuter % 60 print("Det är ", timmar, " timmar och ", minuter, " minuter")
""" created by: Ritam Basu created on:06/11/19 created for: assignment1. """ from math import * def f(x,y): return (x+y) #adding two strings x= "hello" y= "world" print ("addition: ",f(x,y)) #adding two lists x= [1,2,3] y= [4,5,6] print ("addition: ",f(x,y)) #adding floating points x= float(1.5)...
import requests from bs4 import BeautifulSoup s = "If Comrade Napoleon says it, it must be right." a = [100, 200, 300, 400, 500] def foo(arg): print(f'arg = {arg}') class Foo: url = "https://www.python-course.eu/sys_module.php" page = requests.get(url) print(page) soup = BeautifulSoup(page.cont...
class Bank: def __init__(self): self.accounts = [] class Account: def __init__(self, no, cust): self.no = no self.cust = cust class Costumer: def __init__(self, name): self.name = name b = Bank() c = Costumer('Flemming') b.accounts.append(Account(1234, c)) print(b.accou...
import json import datetime def convert_seconds_to_time(x): converted_time = datetime.timedelta(seconds=x) return converted_time with open("acdc.json", "r") as file: file_dict = json.load(file) overall_data_for_count_duration = file_dict["album"]["tracks"]["track"] def parse_time_duration(value):...
import datetime created = input("Enter the time to check (small hint day-month-year): ") def convert_numbers_to_date(date): created_dt = datetime.datetime.strptime(created, "%d-%m-%Y") converted_time = created_dt.strftime("%d-%m-%Y") return converted_time print(convert_numbers_to_date(created))
factorial = 1 number_for_factorial = int(input("Enter a number to find factorial: ")) if number_for_factorial < 0: print("We can't find factorial of negative number") elif number_for_factorial == 0: print("Factorial for zero is 1") else: for number in range(1, number_for_factorial + 1): factorial = ...
class Ship: """ this class simulates a spacecraft in the "Asteroids" video game """ def __init__(self, place_x, speed_x, place_y, speed_y, direction): """ the constructor for class ship :param place_x: the location of the ship on x axis :param speed_x: the speed of the s...
num = 1 # setting our initial number while True: # setting an infinite loop if 9*num > 100: break # exits loop if multiple of 9 is greater than 100 print(9*num) # prints multiple of 9 num = num + 1 # adds 1 to the number
""" The DisjointSets module provides a class that represents sets of integers in the half-open interval [0..n). When first creating an instance of the class, it will contain n sets, with each integer in a set of its own: >>> ds = DisjointSets(5) >>> ds.size 5 >>> str(ds) '0: [0], 1: [1], 2: [2], ...
""" recurse.py ~~~~~~~~~~ Provides a Maze generator using recursive memory. It This algorithm runs quite fast, but takes some memory (proportional to height*widht) TODO: insert example image """ from random import randint, shuffle __author__ = 'Reindert-Jan Ekker' from amaze.maze import NORTH, SOUTH, WEST, EAST, M...
# Question: Add a new pair of key (e.g. c ) and value (e.g. 3 ) to the dictionary and print out the new dictionary. # # d = {"a": 1, "b": 2} # Expected output: # # {'a': 1, 'c': 3, 'b': 2} d = dict({"a": 1, "b": 2}) d['c'] = 3 print(d)
# Create a dictionary of keys a, b, c where each key has as value a list # from 1 to 10, 11 to 20, and 21 to 30 respectively. Then print out the dictionary in a nice format. # from pprint import pprint d = {"a": list(range(1, 11)), "b": list(range(11, 21)), "c": list(range(21, 31))} pprint(d) print(d)
# Plotting percentage of women who received an engineering degree over years # importing bokeh and pandas from bokeh.plotting import figure from bokeh.io import output_file, show import pandas # prepare some data df = pandas.read_csv("http://pythonhow.com/data/bachelors.csv") x = df["Year"] y = df["Engineering"] # p...
def fibonacci(n): f1 = 0 f2 = 1 if n ==0: return f1 if n == 1: return f2 for _ in range(1, n): f1, f2 = f2, f1 + f2 return f2
""" Formatter to provide logs in a Python dictionary format which can be used by the OpenTracingHandler """ from abc import ABC, abstractmethod from io import StringIO from logging import Formatter, LogRecord import sys import traceback from typing import Dict, Optional from opentracing import logs from opentracing.e...
x = 13 y = 42 a = [y, y + x, y + 2 * x] for k in a: print(k, "mod", x, "=", k % x) print("och därmed är alla kongruenta i", x)
def a(n): return 5 * (2 ** n) - 3 print("Rekursiv formel def: a(0) = 2,") print("a(n + 1) = 2a(n) + 3") print() print("Sluten formel def: a(n) = 5 * 2 ^ (n) - 3") print("a(0) =", a(0)) print("a(n + 1) = 5 * 2 ^ (n + 1) - 3") print() print("Bevis att Rekursiv == Sluten:") print("Rekursiv a(n+1) av Sluten a(n):") prin...
import random rand_num = random.randint(0,2) if rand_num == 0: computer = "rock" elif rand_num == 1: computer = "paper" else: computer = "scissors" print("...rock...") print("...paper...") print("...scissors...") player = input("player enters: ").lower() print(f"computer plays {computer}" ) pri...
class Grid: def __init__(self, puzzle = 81*'.'): """ Constructeur par défaut Arguments : - puzzle : chaine de 81 caractères Tests : >>> Grid().puzzle == 81*'.', Grid(81*'2').puzzle == 81*'2' (True, True) >>> Grid()....
# Create a Python program that picks a number at random which you must guess within 5 chances. import random print("", "The computer has selected a number from 1 to 100. You have 5 tries to guess it", sep="\n" ) secret_number = random.randint(1, 100) chances = 5 def game(chances, secret_number): ...
# -*- coding: utf-8 -*- from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf def dnn(x): W_hidden = weight_variable([784, 500]) b_hidden = bias_variable([500]) h_hidden = tf.nn.relu(tf.matmul(x, W_hidden) + b_hidden) keep_prob = tf.placeholder(tf.float32) h_hidden_drop = t...
''' Runtime: 40 ms, faster than 97.87% of Python3 online submissions Depth-First Search ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: paths = [] def binaryTreePaths(self...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: nodes = [] def dfs(self, root): if root: self.dfs(root.left) self.nodes.append(root.val) ...
''' Runtime: 64 ms, faster than 75.01% of Python3 online submissions ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: flag = True def isBalanced(self, root: TreeNode) -> bool: ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': self.father = {} self.fathe...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def middleNode(self, head: ListNode) -> ListNode: n = 0 it = head while it: n += 1 it = it.next # ca...
''' 64 ms 通过递归求二叉树最大最小值判断是否符合二叉搜索树的条件 ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: valid = True def maxNode(self, root): # this BST has been proved to be invlal...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: it = head if not it: return None while it.next: if it.next.va...
class Solution: def moveZeroes(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ length = len(nums) it = 0 while it < len(nums): while it<len(nums) and nums[it] == 0: nums.pop(it) it +...
''' Runtime: 40 ms, faster than 63.49% of Python3 online submissions ''' class Solution: def thirdMax(self, nums: List[int]) -> int: numsSet = set() for n in nums: numsSet.add(n) nums = [] for n in numsSet: nums.append(n) nums.sort(reverse=True) ...
class Solution: # judge if str1 is the 'substring' of str2 def substring(self, str1, str2): len1, len2 = len(str1), len(str2) it1, it2 = 0, 0 while it1 < len1 and it2 < len2: if str1[it1] == str2[it2]: it1 += 1 it2 += 1 else: ...
#!/usr/bin/python # -*- coding: utf-8 -*- class fraction: def __init__(self,top,bottom): self.num=top self.den=bottom def __str__(self): return str(self.num)+"/"+str(self.den) def show(self): print self.num,"/",self.den def __add__(self,otherfraction)...
class Poly: def __init__(self,liste1): self.one=liste1 def __add__(self, off): if len(self.one)>len(off.one) or len(off.one)>len(self.one): if len(self.one)>len(off.one): while len(self.one)>=len(off.one): off.one.append(0) ...
# cleaning up data import pandas as pd from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import Polygon from matplotlib.pyplot import figure, show ## DATA LISTS def panda_to_list(file_name, title1): """ The opens a saved csv file and conver...
class Throw(object): def __init__(self): self._value = None self._name = None def __gt__(self, other): if not isinstance(other, Throw): return NotImplemented x = self._value - other._value return x == -1 or x == 2 @property def name(self): re...
from typing import Tuple import time count = 0 start_time = 0 end_time = 0 #Read input data from file def readFile(fileName): f = open(fileName, "r") equation = f.readline() f.close() return equation #Write the result to file def writeFile(fileName, cryptaSolu, assignment): f = op...
#Length of LL """ For a given singly linked list of integers, find and return its length. Do it using an iterative method. Input format : The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow. First and the only line of each test case or query co...
#Find path in BST """ Given a BST and an integer k. Find and return the path from the node with data k and root (if a node with data k is present in given BST). Return null otherwise. Assume that BST contains all unique elements. Input Format : Line 1 : Elements in level order form (separated by space) (If any node do...
#Remove X """ Given a string, compute recursively a new string where all 'x' chars have been removed. Input format : String S Output format : Modified String """ Sample Input 1 : xaxb Sample Output 1: ab Sample Input 2 : abc Sample Output 2: abc Sample Input 3 : xx Sample Output 3: Solution : def removeX(s,x): ...
# -*- coding: utf-8 -*- # Autor: Enmanuel Cubillan # Programa que muestra la tabla de multiplicar de cualquier número # Bucle For In numero = int(raw_input('Ingrese un número: ')) print '\nTabla de Multiplicar\n\n ' + str(numero) print '____________' for i in [1,2,3,4,5,6,7,8,9,10]: print '%d x %d = %d' %(i,nume...
# -*- coding: utf-8 -*- # Autor: Enmanuel Cubillan # Programa de registro de personas, además nos dice quien es el (la)\ # menor y el (la) mayor con respecto a su edades nombre = [0 for x in range(0,3)] edad = [0 for x in range(0,3)] aux = [0 for x in range(0,3)] for i in range(0,3): nombre[i] = (raw_input('Ingr...
# -*- coding: utf-8 -*- # Autor: Enmanuel Cubillan # Programa que cuenta la cantidad de números pares, impares o ceros entrar = True contar_par = 0 contar_impar = 0 contar_ceros = 0 print 'Programa que cuenta la cantidad de números pares, impares o ceros' while(entrar): cantidad = int(raw_input('Ingrese la cant...
class user: def __init__(self,name,age,email,n1,n2): self.name=name self.email=email self.age=age self.balance=[BankAccount(n1,n2)] def newbankaccount(self,n1,n2): self.balance.append(BankAccount(n1,n2)) def withdraw(self,amount,banknum): self.balance...
a=[] b=[] c=[] t=int(input('enter no of rows and columns')) print('enter elements in a') for i in range(t): s=[] j=0 for j in range(t): s.append(int(input())) a.append(s) print('enter elements in b') for i in range(t): s=[] j=0 for j in range(t): s.append(int(input())) b.append(s) for i in range(t): s=[] ...
class Products(): def __init__(self,price,item_name,weight,brand,cost,status): self.price = price self.item_name = item_name self.weight = weight self.brand = brand self.cost = cost self.status = status def sell(self): self.status = "sold" def return_r...
class Car(): def __init__(self,price,speed,fuel,mileage): self.price = price self.speed = speed self.fuel = fuel self.mileage = mileage def tax(self): if self.price > 10000: self.tax = self.price * 0.15 else: self.tax = self.price * 0.12 ...
import random def guess(x) : random_number = random.randint(1, x) guess = 0 while guess != random_number : guess = int(input(f'Enter a random number between 1 and {x}: ')) if guess > random_number : print('Sorry guess again. Your guess was too high \n') elif guess < rand...
userChoice = 0 workArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] def doOperation(n): if n == 1: print(" ".join(map(str, workArray))) elif n == 2: print("Введите значение, которое хотите добавить") result = int(input()) workArray.append(result) p...
# -*- coding: UTF-8 -*- import functions from functions import file_encrypt, file_decrypt, printCN, raw_inputCN while 1: # 相当于主程序了。。。 printCN("这是一个加解密文件程序,请按照提示输入!\n") printCN("请选择:\n1.加密文件 2.解密文件 3.退出") select = input() if select == 1: file_encrypt...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Вхідні дані: 2 невід'ємних дійсних числа a та b -- аргументи командного рядка. b не дорівнює 0. Вихідні дані: дійсне число -- результат обчислення формули """ import sys, math; x=float(sys.argv[1]); y=float(sys.argv[2]); z=float(sys.argv[3]); part1=(1 / (z * math.s...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Розробити функцію counter(a, b), яка приймає 2 аргументи -- цілі невід'ємні числа a та b, та повертає число -- кількість різних цифр числа b, які містяться у числі а. Наприклад Виклик функції: counter(12345, 567) Повертає: 1 Виклик функції: counter(1233211, 1212...
#!/usr/bin/python3 def list_division(my_list_1, my_list_2, list_length): que_list = [] for i in range(list_length): que = 0 try: que = my_list_1[i] / my_list_2[i] except (ZeroDivisionError, ValueError): print("division by 0") except IndexError: ...
#!/usr/bin/python3 def print_list_integer(my_list=[]): leng = len(my_list) for i in my_list: print("{:d}".format(i))
#!/usr/bin/python3 """ contains method to load object from JSON file """ def load_from_json_file(filename): """Load object from JSON""" import json with open(filename, mode="r", encoding="utf-8") as f_name: return json.load(f_name)
#!/usr/bin/python3 def no_c(my_string): charr = "" i = 0 for char in my_string: if ord(char) == ord('c') or ord(char) == ord('C'): char = "" charr = charr + char return charr
#!/usr/bin/python3 import random number = random.randint(-10000, 10000) str = "Last digit of " if number >= 0: rem = number % 10 else: rem = number % (-10) if rem > 5: print(str + "{} is {} and is greater than 5".format(number, rem)) elif rem == 0: print(str + "{} is {} and is 0".format(number, rem)) ...
# import csv import os import csv #List FinAnalysis variables to solve Ttl_Months = 0 Ttl_PL = 0 Prior_PL = 0 Change_PL = 0 MoM_Change = 0 Greatest_Increase_Profits = 0 Greatest_Decrease_Profits = 0 # specify csv file path csvpath = os.path.join('Resources','budget_data.csv') #open csv with open(csvpath) as csvfile...
# -*- coding: utf-8 -*- import random import datetime s = "abcdefghijklmnopqrstuvwxyz" def random_string(size): l = [] for i in range(size): l.append(s[random.randint(0, len(s) - 1)]) return "".join(l) # 朴素算法 def algorithm1(src, target): for i in range(len(src)): flag = True ...
# largest prime factor of given number N #T = int(raw_input().strip()) def rwh_primes1(n): # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 """ Returns a list of primes < n """ n = int(n) sieve = [True] * int(n/2) for i in range(3,int(n*...
print("\n*************************** Calculator performed calculation for Two Numbers ********************************\n") num1 = float(input("Enter First Number : ")) num2 = float(input("Enter Second Number : ")) operator = input("Enter Operator (+ , - , * , / , %) : ") print("\n") if(operator == '+'): pri...
student_marks={"john":86.5,"jack":91.2,"jill":84.25,"harry":72.1,"joe":80.5} print(student_marks) asc=(sorted(student_marks.values())) print(asc) l=len(asc) d=[] while l!=0: d.append(asc[l-1]) l=l-1 print("descending order=",d) print(sum(student_marks.values())/float(len(student_marks))) ...
#!/usr/bin/python3 #_*_ coding:utf-8 _*_ def count_str(str): digit_num=0 char_num=0 space_num=0 other_num=0 for i in str: if i.isdigit(): digit_num+=1 elif i.isalpha(): char_num+=1 elif i.isspace(): space_num+=1 else: other_num+=1 print("数字:%d"%(digit_num)) print("字母:%d"%(char_num)) print(...
class Solution(object): def sumNumbers(self, root): """ :type root: TreeNode :rtype: int """ result = [0] self.sumNumbersRecursive(root, 0, result) return result[0] # Need collect all the information of paths from root to leaf. This ...
# Step 1: Use simple exampe to get familiar with question # Use example to generate BST # for example: [1, 2, 3] can generate # 1 | 1 # 2 | 3 # 3 | 2 # # 2 # 1 3 # # 3 | 3 # 2 | 1 # ...
# standard traversal problem class Solution(object): def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ # leaf condition if root == None: return 0 # skeleton, since function has return, need to assign variables for followin...
import os import datetime as dt def exists(file): '''checks if a file exists (in docs folder) input: filename''' return os.path.isfile(file) def tdate(): '''Gives current date in string form''' return str(dt.date.today())
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv 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) """ TASK 1: How many different telephone num...
# pylint:skip-file from typing import List class Solution: def search(self, nums: List[int], target: int): for idx, num in enumerate(nums): if num == target: return idx return -1 solution = Solution() input_nums = [4, 5, 6, 7, 0, 1, 2] input_target = 0 ans = soluti...
import unittest from unique_words_count import unique_words_count class UniqueWordsCountTests(unittest.TestCase): def test_cases(self): input_1 = ["apple", "banana", "apple", "pie"] input_2 = ["python", "python", "python", "ruby"] input_3 = ["HELLO!"] * 10 self.assertEqual(3, uniq...
import sqlite3 class CompanyCreator: def __init__(self, file_name): self.connect = sqlite3.connect(file_name) self.cursor = self.connect.cursor() self._fill_db() def __del__(self): self.connect.close() def _fill_db(self): self.cursor.execute('''CREATE TABLE IF NO...
from functools import reduce class Board: EMPTY = ' ' USER = 'X' AI = 'O' USER_WIN = 3 AI_WIN = -3 DRAW = 1 NOT_OVER = None def __init__(self): self.state = [[self.EMPTY for col in range(3)] for row in range(3)] self.is_user_turn = True def make_move(self, player_...
from time import time from datetime import datetime class Pizza: def __init__(self): self.order = {} self.orderNames = [] self.isListCalled = False self.isLastOrderSaved = True self.finishCount = 0 def loadOrder(self, orderName): order = {} with open(o...
from db_manager import DBManager from question import Question class GameCLI: def __init__(self): self.db = DBManager() self.player_name = '' def game_start_up(self): first_msg = 'Welcome to the \"Do you even math?\" game!\n' first_msg += 'Here are your options:\n- start\n- hi...
from sum_matrix import sum_matrix import copy def handle_neighbour(m, (x, y), bomb): if x >= 0 and x < len(m[0]) and y >= 0 and y < len(m): if m[y][x] >= bomb: m[y][x] -= bomb else: m[y][x] = 0 def blow_bomb(m, (x, y)): bomb = m[y][x] for x_pos in range(x-1, x+2):...
def addNumbeer(first, second): return first + second print(addNumbeer(1, 2)) myString = "Hello Roman" print(myString[0:3]) # chars from 0 to 2 print(myString[-3:]) # last 3 chars print(myString[:-3]) # full string except last 3 chars print(myString[:5] + " Romchik") # concatenation of first 5 chars and w...
''' Exemplos de números primos? 7, 11, 13, ... ''' def primo(n): contDiv = 0 for i in range(1, n+1): if n % i == 0: contDiv += 1 if contDiv <= 2: return True return False print(primo(11))
import numpy as np import pandas as pd class DataFile(): """ A class encapsulating the data files. One of such object encapsulates one data file produced by a single sensor during a single trial or traversal of the stairs. Therefore, three such objects encapsulate the data for a trial (one for each sen...
print('#### POWERS THEN AMPERAGES ####') data = [float(x) for x in input().split()] amperages = [float(x) for x in input().split()] powers = [] r_mini = 0.073 r_big = 0.177 n = 600.0 print() for i in range(1, len(data), +2): powers += [float(data[i-1] + data[i])] for i in range(len(powers)): print(i,'| P ='...
#!/bin/python3.7 import pyperclip Passwords = {} def SearchInDictByKey(key, dict): # if len(dict) == 0: # return 0 for x in dict.keys(): if str(x) != key: return 1 if str(x) == key: for y, z in dict.items(): if x == y: return...
name = input("What is your name? ") msg = "Hello World!" output = name + " says: " + msg print(output) # del output output = None things = ["yay", "yes", "no", "nope"] for thing in things: print(thing) def check_message_status(): if bool(output) == False: print("What happened to my message?") elif output:...
big_list = list(range(1,50)) print big_list everything_even = big_list[1::2] print everything_even words = "Thisisanexamplestringfulloflettersnospaces" print words[::-1] middle_chunk_backwards = big_list[30:10:-1] print middle_chunk_backwards def sillycase(thing): thing = thing.lower() middle = len(thing)/2...
""" It is a six-digit number. The value is within the range given in your puzzle input. Two adjacent digits are the same (like 22 in 122345). Going from left to right, the digits never decrease; they only ever increase or stay the same (like 111123 or 135679). Other than the range rule, the following a...
# find the number of ways to get to position # x, y # in a matrix of MxN, eg 3 x 5: """ [[0], [0], [0], [0, [0]] [0], [0], [0], [0, [0]] [0], [0], [0], [0, [0]]] Starting from [0][0], find your way to [M][N], and return the number of all possible paths """ """ Lets use the same Framework 1. Define the objective f...
# given two strings S and T, return if they are equal # if the strings contain a # symbol, it is a backspace # therefore deleting the previous character def solution(s, t): s_pointer = len(s) - 1 t_pointer = len(t) - 1 s_skip = 0 t_skip = 0 while s_pointer >= 0 or t_pointer >= 0: while s...
import os import csv os.getcwd() #Create month Values #Create lists for data that is held in csv file Date = [] Profit_Loss = [] month_year = [] year = [] month = [] beginning_month_value = 0 ending_month_value = 0 #Create variable to track metrics for average change in profit or loss, the max change in profi...
A = True B = True C = False D = True E = False print(type(A)) print(A and B) # True print(A and C) # False print(D and E) # False print(D or E) # True print(not A) # False print(not not A) # True # And: takes two inputs and outputs the when they're both true # A | B | outputs # -----------------...
# Given an array of ints, return a new array with # the elements in reverse order, so {1, 2, 3} becomes {3, 2, 1}. # reverse([1, 2, 3]) → [3, 2, 1] # reverse([5, 11, 9]) → [9, 11, 5] # reverse([7, 0, 0]) → [0, 0, 7] # 0, 1, 2, 3, 4 my_list = [1, 2, 3, 4, 5] def reverse(my_list): rev_list = [] for in...
# print 20, 22, 24, 26, and 28 # range(start, end, how many to add each time) for number in range(20, 30, 2): print(number) # how do you write this as a while loop? i = 20 while i < 30: print(i) i = i + 2 # how many times does this run? # 10 i = 10 while i > 0: print(i) i -= 1 # how many times d...
for i in range(10): print(i) arr = [i for i in range(10)] print(arr) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] arr[4] = 100 arr[8] = 800 print(arr) # [0, 1, 2, 3, 100, 6, 7, 800, 9] arr = [2*i + 1 for i in range(5)] # [0, 1, 2, 3, 4] # [1, 3, 5, 7, 9] print(arr) # [1, 3, 5, 7, 9] arr = [i**2 for i in range(7)] print(arr...
# Script for generating dictionaries from a corpus # One dictionary is generated directly from the corpus without stemming # while the other is generated after the words in the corpus are stemmed # with Porter's algorithm # This file also contains code for generating basic information about # the two dictionaries...
''' Based on the seive of Eratosthenes, this code gives a list of primes within a given compact interval and also a sublist of those which are Mersenne primes also. ''' from math import log def seive(a,b): # begin with all numbers in [2,b] primes = range(2,b+1) # and [a,b] atob = range(a,b+1) # filte...
from typing import List from collections import deque class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: intervals.sort(key=lambda x: x[0]) res=[] for item in intervals: if res and res[-1][1]>=item[1]: continue elif res a...
from typing import List class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: results=[] def dfs(start,arr): results.append(arr) for i in range(start, len(nums)): dfs(i+1, arr+[nums[i]]) dfs(0,[]) return results sol=Solutio...
import random class MinCut: """ Compute the minimum cut of a connected graph using Karger's algorithm with edge contraction """ def __init__(self, graph, runs=lambda n: 2*n): """ Compute the minimum cut for a given graph, with number of iterations defined by runs function ...
# In this assignment you must do a Twitter search on any term # of your choice. # Deliverables: # 1) Print each tweet # 2) Print the average subjectivity of the results # 3) Print the average polarity of the results # You will demo this live for grading. import tweepy from textblob import TextBlob # Unique code from T...
import leiafloat, leiaint m = leiafloat.leiafloat("Digite um float: ",-10.3,6) n = leiaint.leiaint("Digite um inteiro: ",-5,3) print(m) print(n)
# The Adventures of Bob the Turtle (Turtle Bob) # # This is the main module for this application. # #Import the time module so that we can delay for times and such import time #Import the atexit module so we can have a graceful and consisten exit # from the program import atexit #Import terminalsize.py so we can get ...
# this is a comment print('hello world') print('comment is not printed') print('hello Python') # print("This shouldn't print") print("this should print") print('hello','Juliana','Giolo') """ this add comments in more than one line """ print('Hello,') print('Juliana Giolo') print('Hello','Giolo')
myname=input("what is your name") print("hello"+myname)