text
stringlengths
37
1.41M
# Shifts the numbers in a list (left or right) circularly by some # integer amount # Unless stated otherwise, variables are assumed to be the list data type def left_shift(N, k_int): """Given a list of N numbers, function shifts the numbers circularly by some integer k_int (where k < N). Returns the shifte...
# -*- coding: utf-8 -*- """ Created on Fri Jul 6 10:50:55 2018 @author: Pshypher """ # Prompt user for file_name, open file if found otherwise re-prompt for # file_name # Iterate through each line of the .csv, split each row on a comma (',') and # assign the resulting list to a variable for each row in the .csv fi...
# Program designed to make payment on a credit card with a credit limit of $1000 # the minimum payment due is always $20 import random CREDIT_LIMIT = 1000 DEBT = random.random() * CREDIT_LIMIT def make_payment(P): """ Makes payment on a credit card.""" MINIMUM_PAYMENT = 20 valid_payment = False...
# -*- coding: utf-8 -*- """ Created on Sat Aug 4 16:34:51 2018 @author: Pshypher """ import random import math class WayPoint(object): DISTANCE_PER_DEGREE_LATITUDE=110.57 # distance in km per degree lat. DISTANCE_PER_DEGREE_LONGITUDE=111.32 # distance in km per degree long. def __init__(...
# -*- coding: utf-8 -*- """ Created on Tue Aug 21 23:07:58 2018 @author: Pshypher """ class Vehicle(object): def __init__(self, model_year, vehicle_id, epa_class, engine, transmission, options, epa_mileage=0, mileage=0): print('in vehicle constr') self.__model_year = model_y...
# -*- coding: utf-8 -*- """ Created on Sun Jul 15 09:19:59 2018 @author: Pshypher """ def open_file(): '''Prompts user for the name of a file containing a list of words, and returns a file object that contains the list of words.''' found = False while not found: try: file_name = i...
# -*- coding: utf-8 -*- """ Created on Tue Jul 10 16:16:04 2018 @author: Pshypher """ def to_lowercase(name_str: str) -> str: '''Converts each character in a name to lowercase ascii characters.Returns a string.''' name_lower_str = '' for char in name_str: name_lower_str = name_lower_str + cha...
# Calculates the depth of the great lakes in the United States over a # surface area of the 48 contiguous states. volume_int = 22810 # Volume of 22% of the world's fresh surface water surface_area_int = 8080464.3 # Surface area in square km # V = SA * H # where V is the volume, SA the surface area and # H is the...
# Unless stated otherwise, variables are assumed to be of the str data type def reverse_string(S): """Return the string S in reverse order using a for loop.""" S_reverse = "" for ch in S: S_reverse = ch + S_reverse return S_reverse # Prompt user for a string chars = input("Enter a sequence of...
# Program written to English words into their Pig Latin form # Prompt user for an english word # Change the case of the word (lower case) # If the user enters a word other than the string corresponding to "quit" # If the first character of the string is a vowel, append "way" to the end # of the word # Othe...
## ## Demonstrate some of the operations of the Deck and Card classes ## import cards # Seed the random number generator to a specific value so every execution # of the program uses the same sequence of random numbers (for testing). import random random.seed(100) # Create a deck of cards my_deck = cards.Deck() #...
# Program designed for the purposes of substring matching with applications # in genetics, such as trying to find a substring of bases ACTG # (adenine, cytosine, thymine and guanine) in a known DNA string, or # reconstructing an unknown DNA string from pieces of nucleotide bases # Unless stated otherwise,all variables...
# -*- coding: utf-8 -*- """ Created on Wed Aug 8 13:09:04 2018 @author: Pshypher """ class OnlineBook(): def __init__(self,title_str,publisher_str,price_flt,author_list,isbn): """Initialize an instance of the class.""" self.__title = title_str self.__publisher = publisher_str ...
# Program written to calculate the total distance of the # Voyager 1 spacecraft from the sun since September 15, 1977 current_distance_int = 16637000000 # total distance as of September 25, 2009 in miles speed = 38241 # speed in miles/hour speed_of_rw_ms = 299792458 # speed of light in meters/second # Prompt...
from player_abstract import MyPlayer as AbstractPlayer # for analysing how much time remaining does the player have to think import time # for infinity. Infinity is cool import math class MyPlayer(AbstractPlayer): '''This is player that tries to predict what the score will be next turn or more turns after that ...
import random as rand import gettext import os import sys import locale def main (): #capital es la cuantitat de diners de la que disposem # aposta es la cuantitat de diners que apostem # numero es el numero al qual apostem # sorteig es el numero que surt a la ruleta # nguanyades es el contador de les partides qu...
# coding: utf-8 # In[ ]: from random import randint player1Score=0 player2Score=0 computerScore=0 # game logic to choose who is the winer and calculate Scores for players def gameLogic(player1,player2,score1,score2): if player1 == player2: print('Tie') elif player1 =="rock": ...
from collections import deque stacks = [ deque(), deque(), deque(), deque(), deque(), deque(), deque(), deque(), deque(), ] def split_stacks(line: str): global stacks row = ( line[1], line[5], line[9], line[13], line[17], lin...
def printmatrix(m, l): line = [] for i in range(l): for j in range(l): line.append(m[i, j]) print(line) line = []
import math import os import random import re import sys #Function to calculate number of apples and oranges def countApplesAndOranges(s, t, a, b, apples, oranges): count_apples = 0 count_oranges= 0 for i in range(len(apples)): if a+apples[i] >= s and a+apples[i] <= t: count_apples +=1...
#Function to add array elements def add_arr(arr): sum = 0 for i in arr: sum = sum + i return (sum) #Driver Code arr=[] n=int(input("Enter number of array elements:")) for x in range(n): ele=int(input("Enter element:")) arr.append(ele) ans = add_arr(arr) print(ans)
# Check for Palindromes # Return true if the given string is a palindrome. Otherwise, return false. # A palindrome is a word or sentence that's spelled the same way both forward and backward, ignoring punctuation, case, and spacing. #Note #You'll need to remove all non-alphanumeric characters (punctuation, spaces and ...
# Confirm the Ending # Check if a string (first argument, str) ends with the given target string (second argument, target). def confirmEnding(str, target): return str[(len(str) - len(target)):]==target print (confirmEnding("Bastian", "n")) #should return true. print (confirmEnding("Connor", "n")) #should return fa...
# Search and Replace ''' Perform a search and replace on the sentence using the arguments provided and return the new sentence. First argument is the sentence to perform the search and replace on. Second argument is the word that you will be replacing (before). Third argument is what you will be replacing the second ar...
# Logging - Example 2 """ Level Description -------------------------------------------------------------------------------- DEBUG Detailed information, typically of interest only when diagnosing problems. INFO Confirmation that things are working as expected. WARNING An indication tha...
# SUBPROCESS import subprocess """ Communicate from the script to the shell and get the output """ """ The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. https://docs.python.org/3/library/subprocess.html """ """ ...
import unittest class Stack: def __init__(self, size=10): self.items = size * [None] # utworzenie tablicy self.n = 0 # liczba elementów na stosie self.size = size def is_empty(self): return self.n == 0 def is_full(self): return self.size...
from main import Frac #Unit tests for fracs import unittest class TestFractions(unittest.TestCase): def setUp(self): self.zero = Frac(0, 1) self.f1 = Frac(-1, 2) self.f2 = Frac(0, 1) self.f3 = Frac(3, 1) self.f4 = Frac(6, 2) self.f5 = Frac(0, 2) self.f6 = Frac(9, 2) self.f...
class Edge: """Klasa krawędzi (okreslanie wagi,wierzchołki poczatkowe i koncowe krawedzi)""" def __init__ (self, start_node, end_node, weight = 1): self.start_node = start_node self.end_node = end_node self.weight = weight def __repr__(self): """Reprezentacja kra...
a = ("ram" , "rohit" , "mohit" , 2 20.4 ) print(a) # update function does not support in tuple ....while list supports it . a[0] = "abc" # no update b = () #empty tuple b = (1) # integer type not tuple b = (1 , ) # tuple
class QuickSort: def __init__(self, vector): if vector == None: raise Exception('Vetor Nulo!') elif len(vector) <= 1: raise Exception('Tamanho invalido!') else: self.__vector = vector def partition(self, start, end): i = start - 1 ...
# Class matrix calculation: create a class for 3 functions. # Function 1: save a random matrix in a txt file. # Function 2: get the inner product of m random matrices, one of the matrices is from Function 1 # Function 3: Read the results of the matrix from Function 1 and Function 2. #l*l rondom matrix #m: # of matric...
salario = float(input(' Qual é o salario do funcionamento? R$')) novo = salario + (salario * 15/100) print('Um funcionario que ganhava R${:.2f}, com 15% de aumento, passa a receber R${:.2f}'.format(salario, novo))
print('{:=^40}'.format('LOJA DE ISRAEL ')) preco = float(input('Preços das compras: R$')) print('''FORMAS DE PAGAMENTOS [1] à vista dinheiro/cheque [2] à vista cartão [3] 2x no cartão [4] 3x ou mais no cartão''') opcao = int(input('Qual é a opçao? ')) if opcao == 1: total = preco - (preco * 10/100) elif opcao == 2:...
from random import randint from time import sleep itens = ('PEDRA', 'PAPEL', 'TESOURA') computador = randint(0,2) print('''Suas opçoes: [0] pedra [2]papel [3] tesoura''') jogador = int(input('Qual é sua jogada? ')) print('JOO!!!') sleep(1) print('KENN!!!') sleep(1) print('POO!!!') print('-='*12) print('Cmputador jogou ...
times = ('Corinthians','Palmeiras','Santos','Gremio', 'Cruzeiro','Flamengo','Vasco','Chapecoense', 'Atletico','Botafogo','Atletico-PR','Bahia', 'Sao paulo','Fluminense','Sport','EC Vitoria', 'Coritiba','Avai','Ponte Preta','Atletico-GO') print('-='*15) print(f'Lista de times: {times}...
num = (int(input('Digite um numeros:')), int(input('Digite outro numeros:')), int(input('Digite mais um numeros:')), int(input('Digite o ultimo numeros:'))) print(f'Voce digitou os valores {num}') print(f'O valor 9 apareceu {num.count(9)} vezes') if 3 in num: print(f'O valor 3 apareceu na {num....
# Clump Finding Problem # Find patterns forming clumps in a string. # Input: A string Genome, and integers k, L, and t. # Output: All distinct k-mers forming (L, t)-clumps in Genome. def frequencyMap(text, k): freqMap = {} n = len(text) for i in range(n - k): pattern = text[i:i + k] if pa...
import random import numpy as np class State: dealercard = random.randint(1,10) playersum = random.randint(1,10) # adds some drawn card value def drawcard(current): if random.randint(1,3) < 3: current += random.randint(1,10) else: current -= random.randint(1,10) return current # a...
class Car: wheels = 4 #This is a class variable def __init__(self):# All the variables inside init are instance variables self.mil = 10 self.com = "BMW" ### If we ant to change the value of class variables Car.wheels = 5 #This is the way to change ...
def insertSort(A:list): for j in range(2,len(A)): for i in range(j-1,0,-1): if(A[i]>A[i+1]): t = A[i] A[i] = A[i+1] A[i+1] = t return A A = [4,5,5,7,8,234,746,23425,352345,3] A = insertSort(A) print(A)
''' You are given a string . Your task is to find out whether is a valid regex or not. Input Format The first line contains integer , the number of test cases. The next lines contains the string . Output Format Print "True" or "False" for each test case without quotes. ''' import re for i in range(int(input())): ...
''' Task You are given a X integer array matrix with space separated elements ( = rows and = columns). Your task is to print the transpose and flatten results. Input Format The first line contains the space separated values of and . The next lines contains the space separated elements of columns. Output Format Fi...
''' This tool computes the cartesian product of input iterables. It is equivalent to nested for-loops. For example, product(A, B) returns the same as ((x,y) for x in A for y in B). Task You are given a two lists A and B.Your task is to compute their cartesian product A X B. Input Format The first line contains the sp...
''' Task The students of District College have subscriptions to English and French newspapers. Some students have subscribed only to English, some have subscribed only to French, and some have subscribed to both newspapers. You are given two sets of student roll numbers. One set has subscribed to the English newspaper,...
''' Task You are given a space separated list of nine integers. Your task is to convert this list into a X NumPy array. Input Format A single line of input containing space separated integers. Output Format Print the X NumPy array. ''' import numpy n = list(map(int, input().split())) my_array = numpy.array([n]) x =...
''' Task Given sets of integers, and , print their symmetric difference in ascending order. The term symmetric difference indicates those values that exist in either or but do not exist in both. Input Format The first line of input contains an integer, . The second line contains space-separated integers. The thir...
primelist=[2] number = 3 while primelist[-1]<1000: counter=0 for i in primelist: if number%i==0: counter+=1 if counter==0: primelist.append(number) number+=1 def isprime(num): if num<2: return False count=0 if num in primelist: return True ...
fibonacci = [1,1] new = fibonacci[-1]+fibonacci[-2] while len(str(new))<1000: new = fibonacci[-1]+fibonacci[-2] fibonacci.append(new) print(fibonacci.index(new)+1)
import time start=time.time() pentagon = [i*(3*i-1)//2 for i in range(1,3000)] for a in pentagon: for b in pentagon[pentagon.index(a)+1:]: if b-a in pentagon: if b+a in pentagon: print(f"{b}, {a}, {b-a}") print(f"Time taken: {time.time()-start}")
from time import time start = time() #a/b<3/7 #3b-7a=1 #3b-1 /7 alist = [] for b in range(1000000,6,-1): a=(3*b-1)/7 if a.is_integer(): alist.append([a/b,int(a),b]) alist.sort(reverse=True) print(alist[0]) print(f"Time taken: {time()-start}")
from bs4 import BeautifulSoup html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a h...
def pick(n, list, toPick): if(toPick == 0): print(list) smallest = 0 if not list else list[-1] + 1 for next in range(smallest, n): list.append(next) pick(n, list, toPick-1) list.pop() pick(4, [], 2)
import numpy as np # list_var = [0,1,2,3,4] # arr_var = np.array(list_var, dtype = 'int64') # print(arr_var) #numpy의 array를 출력하면 리스트와 다르게 ','가 없음 # print(arr_var.dtype) # a=[1,3,5] # b=[2,4,6] # result = [] # for ai, bi in zip(a, b): # result.append(ai*bi) # print(result) # a = np.array([[1, 4, 2, 3, 4, 5],[2, 5,...
import pytest # initializing a counter to keep track of individual increasing pairs count = 0 # initializing a variable to keep track of the longest spotted lists maxcount = 0 # initializing a variable to store the index for the last element of # the longest subsequence subindex = 0 def longsubs(intlist): """ ...
""" Author: Sparsh Bansal DSA Homework 5 """ # Importing Python modules import pytest from hypothesis import given import hypothesis.strategies as st import math # Defining the Heap Class class Heap: def __init__(self, oglist = []): ''' Initialize heap from a (possibly empty) list. ''' #...
# -*- coding: utf-8 -*- """ Created on Sat Oct 3 00:26:31 2020 @author: Dana Feldman """ import numpy as np import matplotlib.pyplot as plt ''' Dana Feldman YB4 This neural network predicts if a given person is a male or a female. Males and females have 2 features: height and weight ...
import pandas as pd import math from operator import itemgetter #for knn work with pandas, as we need class aswell which can be character #for indexing and slicing in pandas use .iloc function #given k =3 k= 3 #reading the data dataset = pd.read_csv("/home/omkar/Documents/Untitled1.csv") print(dataset.head()) X = da...
__author__ = 'Jonny' __date__ = '2018.03.14' __location__ = '西安' #利用python实现冒泡排序 '''冒泡排序的稳定是是稳定的''' def maoPaoSort(list): n = len(list) for j in range(0,n-1):#注意和负数下标作区别 for i in range(0,n-1-j): if list[i]>list[i+1]: list[i],list[i+1] = list[i+1],list[i] return list ...
Created by: Austin Wellman if __name__ == '__main__': # printing header all_work = {} all_work['sum'] = [] all_work['print'] = [] print('*** Welcome to the Learn Python Because it is Really Cool Tutorial ***\n') # menu while (True): print("What do you want to learn today...
#This program controls the light smart device #Imports the general file which contains various functions and variables which are used by multiple programs from generalFunctions import * #Importing the GPIO package import RPi.GPIO as GPIO #Setting the server message to blank serverMessage = "" #A function t...
#!/usr/bin/python3 import numpy as np def create_Gaussian_kernel(cutoff_frequency): """ Returns a 2D Gaussian kernel using the specified filter size standard deviation and cutoff frequency. The kernel should have: - shape (k, k) where k = cutoff_frequency * 4 + 1 - mean = floor(k / 2) - standard devia...
#number of bidders set numBidders = int(raw_input("How many bidders are there? ")) #seller sets asking price/opening bid openingBid = int(raw_input("Set the opening bid: ")) bidIncrement = int(raw_input("Set minimum bid increment: ")) #def TelecomAuction(openingBid): openingBidString = str('${:,.0f}'.format((openingBid...
import math # print(eval('type(math.pi)')) # print(eval('1 + 2 * 3')) def eval_loop(): res = None while True: query = input() if query == "done": return res try: res = eval(query) print(res) except: print("Notfound") print(eval_lo...
import math def estimate_pi(): res = 0 k = 0 loop = 0 while True: res += (math.factorial(4 * k) * (1103 + 26390 * k)) / (math.factorial(k) ** 4 * 396 ** (4 * k)) print(str(res)) if loop == 10: break loop += 1 res *= (2 * math.sqrt(2)) / 9801 return 1 ...
def has_no_e(word): return not('e' in word) def avoids(word, c): return not(c in word) def update_list(word, char_list): for c in word: char_list[ord(c) - ord("a")][1] += 1 return char_list def uses_only(word, chars): for c in word: if c in chars: continue retu...
# Christopher Geier (cpg3rb) import random restaurants = ["Sticks", "Yuan Ho", "Melting Pot", "East Garden"] styles = ["Casual", "Chinese", "Fancy", "Chinese"] costs = ["$", "$", "$$$", "$$"] def get_random_restaurant(): index = random.randint(0,3) return restaurants[index],styles[index],costs[index] def g...
import regexs text = ''' CS1110-001/smile ! hi there "hi there" but not " hi there" or "hi there " or "I said "hi" just now" 3,4, 3.0, 4.5 and -3.14159265 1110 but not 3.4.5, 1 or 1 2 or 3 - 4 Thomas Jefferson and Edmund Jennings Randolph and J. Pierpont Finch and T. Jefferson but not T Jefferson or Thomas J. or Fla...
#created on 01/04/2020, 7:13 #author:samuvel list=[]#creating list for sum a=0#naming the variable a and b for the storing of the values of batsman 1 and 2 b=0 over=int(input("enter the number of overs: "))#geting number of overs to clculate number balls bowled overtoballs=over*6#multiplaying 6 with overs to get ...
def format_collection(collection): """ :param dict or set or list or tuple collection: :return: """ if isinstance(collection, set): return def is_collection(o): return (isinstance(o, set) or isinstance(o, tuple) or isinstance(o, list) or isinstance(o, dict)) def format_s...
#s = input() def freq(fruit): # 函数头 result = [] fruit = fruit.lower() flst = fruit.split() unique_fruit = list(set(flst)) for f in unique_fruit: n = flst.count(f) result.append( (f,n) ) # 把(f,n)这个元组添加到result列表后面 return result def sort_in_descending...
import time import math import matplotlib.pyplot as plt def factoring(num): i = 2 output = [] while i <= math.sqrt(num): if num % i == 0: num = num // i output.append(i) else: i += 1 output.append(num) return output start...
# Change all elements of row i and column j in a matrix to 0 if cell (i, j) has value 0 arr = [[0,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]] print(arr) def changeVal(arr): rows= len(arr) cols = len(arr[0]) # if arr[][c] == 0: for i in range(rows): print(i) for j in range(cols): print("----------", j) ...
# Advanced Python Programming for Data Scientists from Data Camp from typing import List import numpy import matplotlib.pyplot as plt import pandas as pd year = numpy.array([1970, 1980, 1990, 2000]) pop = numpy.array([3.5, 4.2, 5.7, 7.1]) # Print the last item from year and pop print(year[-1]) print(pop[-1]) # Make...
''' Experimental code for developing processing of measurement data General Algorithm 1. Store data following process type 2. Clear data associated with storage from memory ''' from datetime import datetime import numpy as np def calculate(processtype,data,storetime): ''' Determines what process function ...
def add(a,b): mlen = max(len(a),len(b)) carry = 0 result = '' a = a.zfill(mlen) b = b.zfill(mlen) for i in range(mlen -1, -1, -1): r = carry r += 1 if a[i] == '1' else 0 r += 1 if b[i] == '1' else 0 result = ( '1' if r % 2 == 1 else '0') + result carry...
# Importing relevant dependencies from bs4 import BeautifulSoup import requests from splinter import Browser import pandas as pd import os import csv def scrape(): # Defining a dictionary for all scraped data: scraped_mars_data = {} # # NASA Mars News # URL of page to be scraped: NASA Mars News Site ...
import re def main(): """Main entry point of the application""" sentence = input('Text: ') print_grade_value(coleman_liau_index(sentence)) def count_total_letters(value): """Count how many alphanumeric characters are in the string""" regex = r'([a-zA-Z])' return len(re.findall(regex, value)) ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 21 21:26:38 2019 @author: krzysztofrozanski """ #Initial packages import numpy as np import pandas as pd import os import matplotlib.pyplot as plt # %% Class definition: class logistic_regression_batchGD(): """Logistic regressor. Cl...
# -*- coding=utf-8 -*- class ListNode(object): def __init__(self, val=0, post=None): self.val = val self.post = post def return_in_array(self): result = [] head = self while head: result.append(head.val) head = head.post return result ...
#-*- coding:utf-8 -*- """ Base Similarity Models. """ #Authors: Marcel Caraciolo <marcel@muricoca.com> #License: BSD Style import numpy as np class BaseSimilarity(object): """ Base Class for similarity that searches over a set of items/users. In all instances, there is a data model against which we wan...
#-*- coding:utf-8 -*- """Utilities to evaluate pairwise distances or metrics between 2 sets of points. """ # Authors: Marcel Caraciolo <marcel@muricoca.com> # Bruno Melo <bruno@muricoca.com> # License: BSD Style. import numpy as np import scipy.spatial.distance as ssd def euclidean_distances(X, Y, square...
nums = [1, 2, 3, 4, 5] for num in nums: if num == 3: print('Found') break print(num) print('\n') for num in nums: if num == 3: print('Found') continue print(num) print('\n') for num in nums: for letter in 'asdf': if letter == 'd': break ...
# https://realpython.com/python-dicts/ # In other laguages called hashmaps or associative arrays # Key must be of a type that is immutable # Key can appear in a dictionary only once # Almost any type of value can be used as a dictionary key (integer, float, Boolean etc) # A tuple can also be a dictionary key, because ...
# 28.集合型 print('===============================') print('---------------') a = {1, 4, 5, 2, 3, 4, 4, 3, 5} # {}で括った、キーのない辞書的なもの print('集合a:', a) print(type(a)) b = {2, 3, 3, 6, 7} print('集合b:', b) print('a - b', a - b) # 集合の引き算(重複する値を取り除く) print('b - a', b - a) # 集合の引き算(重複する値を取り除く)...
'''Convert binary number to decimal''' def anyBinaryToDecimal(binary): result = 0 counter = 1 for i in binary[:-1]: # Iterating through input in reverse order result += int(i) * counter counter = counter*2 return result '''CONSTRUCTION ->''' '''Converts a 32bit integer to a bit array ...
# this program says hello and ask for name print("Hello World!") print("What is your name?") myName = input() print("It is good to meet you, " + myName) print("The length of your name is: ") print(len(myName)) print("what is your age?") myAge = input() print("You will be " + str(int(myAge) + 1) + " in a year.") pa...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # создайте словарь, где ключами являются числа, а значениями – строки. # Примените к нему метод items(), c с помощью полученного объекта dict_items создайте # новый словарь, "обратный" исходному, т. е. ключами являются строки, а значениями – # числа from datetime ...
#zadanie1 ''' else: return lista print(ostatni(lista)) ''' #zadanie2 #chyba dobrze(?) ''' lista_nowa=[] def ogon(lista): if len(lista) > 1: lista_nowa.append(lista[-1]) return ogon(lista[:-1]) else: lista_posortowana=[] for i in range(len(lista_now...
import sqlite3 conn = sqlite3.connect('example.db') c = conn.cursor() # CREATE TABLE c.execute('''CREATE TABLE IF NOT EXISTS main.stocks(date text, trans text, symbol text, quantity real, price real, name text)''') # Altering table by adding column # c.execute('''ALTER TABLE main.stocks ADD COLUMN nam...
import datetime year = datetime.datetime.now().year x = input("Please enter your age: ") print("We think you were born in " + str(year - int(x)))
import datetime t = datetime.time(5, 25, 1) print(t) print(t.tzinfo) today = datetime.date.today() print(today) d1 = datetime.date(2018, 3, 11) d2 = d1.replace(year=2000) print(d2) print(d1 - d2)
even = set(range(0, 40, 2)) print(sorted(even)) print(len(even)) squares_tuple = {4, 6, 9, 16, 25} squares = set(squares_tuple) print(sorted(squares)) print("even minus squares") print(even.difference(squares)) # prints even without values that match squares print("=" * 40) print(even - squares) print("--" * 40)...
# cities = ["Warsaw", "Cracow", "Melbourne", "Canberra"] # with open("cities.txt", 'w') as city_file: # for city in cities: # print(city, file=city_file) cities = [] with open("cities.txt", 'r') as city_file: for city in city_file: cities.append(city.strip('\n')) # removes the \n at the e...
import string with open("letters.txt", 'w') as file: letters = string.ascii_lowercase + " " slice1 = letters[0::3] slice2 = letters[1::3] slice3 = letters[2::3] for letter1, letter2, letter3 in zip(slice1, slice2, slice3): file.write(letter1 + letter2 + letter3 + "\n")
try: for i in ['a', 'b', 'c']: print(i ** 2) except TypeError: print("TypeError occurred: only numbers can be multiplied") try: x = 5 y = 0 z = x / y except ZeroDivisionError: print("ZeroDivisionError: you can't divide by 0") while True: integer = input("Please input integer: ") ...
def word_counter(file): with open(file) as file1: file_reader = file1.read() str_split = file_reader.replace(',', ' ') return len(str_split.split()) print(word_counter('C:\\Users\\mkucman\\Downloads\\words1.txt'))
shopping_list = ["milk", "pasta", "eggs", "spam", "bread", "rice"] for item in shopping_list: if item == "spam": print("I'm ignoring " + item) continue # bypasses item found and goes to another one print("Buy " + item) print("New shopping list:") for item in shopping_list: if item == "spam...
while True: notes = [] password = input("Please input password: ") if not any(i.isdigit() for i in password): notes.append("You need at least one digit") if not any(i.isupper() for i in password): notes.append("You need at least one Uppercase character") if not len(password) >= 5: ...
from dataclasses import dataclass, field @dataclass(order=True) class Country: name: str population: int # repr False causes not showing in the str function, when you print contents of the whole object area: float = field(repr=False, compare=False) coastline: float = 0 def beach_person(self):...