text
stringlengths
37
1.41M
# ARRAYS LESSON # Python arrays are homogenous data structure.They are used to store multiple items but allow only the same type of data. # They are available in Python by importing the array module. # Lists, a built - in type in Python, are also capable of storing multiple values. # But they are different from arrays ...
"""1. Создать список и заполнить его элементами различных типов данных. Реализовать скрипт проверки типа данных каждого элемента. Использовать функцию type() для проверки типа. Элементы списка можно не запрашивать у пользователя, а указать явно, в программе.""" my_list = [1, 2, True, 12.7, ['a', 'b', 'c'], None, 'task...
variable_int = 3215 variable_int_float = 351.235 variable_str = 'Вася Пупкин' variable_list = [1, 2, 7, 'lol'] print(type(variable_list)) user_name = input('Введите ваше имя: ') user_age = int(input("Введите ваш возраст: ")) print(f'Вас зовут {user_name}, Вам {user_age} лет!!! ') print(variable_int + variable_int_float...
# Rječnici u Pythonu osoba = { "ime":"Marko", "prezime":"Marković", "god":18 } print(osoba["ime"]) #ako želimo ispisati određeni ključ print(osoba.get("prezime")) #2. način ako želimo ispisati određeni ključ x = osoba.keys() #ispisuje samo ključeve pošto piše .keys, a da piše .va...
ime = input("unesi svoje ime:") poruka = "dobar dan" print(poruka + " " + ime) a = int(input("unesi broj a:")) b = int(input("unesi broj b:")) print(a+b)
# -*- coding: utf-8 -*- from functions import contain, collect_digits, make_line, make_input from functions import make_line_remainder, make_input_remainder class Exercise: """This is the base class for the individual exercises. An exercise is characterized by a topic. A topic determines the fields of the...
#!/usr/bin/python3 from bs4 import BeautifulSoup import urllib.request from nltk.corpus import stopwords #reading data from URL # GOOGLE web=urllib.request.urlopen('https://www.google.com/') #print or store HTML taged data ##print(web.read()) webdata=web.read() #applying soup souped=BeautifulSoup(webdata,'html5lib')...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns; sns.set(color_codes=True) def generate_point(num_features, num_rows): """ Generate X with an additional column with constant 1.""" X = [] for i in range(num_rows): x = list(np.random.rand(num_features)) ...
########################################################################################### # try : # < this block of code might lead to error # except: # < this block will run when there is error on code # else : # < this block will run where there is no error in code # finally: # < this block will always...
# Python does not require any object to perform file operations like VB script FileSystem object # In Python we can directly use open() function to open file. my_file = open("c:\\ashfaque\\PythonTest.txt") print(my_file.read()) # returns all contents # after every read file cursor moves to at the end of file which c...
# Decorators are used for wrapping given function in some other code. Instead of directly changing # existing code which is prone to introducing new error, we create a decorators which takes function # as argument and run decorators own code before/after running function taken as argument. # So if we have to make chang...
import argparse from teleport.parser import InputParser from teleport.graph import TeleportGraph def main(): """ Main execution function for the script. This is done in a method to scope the variables locally (instead of polluting the module namespace) :return: """ args = _get_argument_parser...
from collections import namedtuple from .error import DataException Route = namedtuple('Route', ['start', 'end']) class CityNode: """Represents a node in the TeleportGraph""" def __init__(self, name): self._name = name self._related_cities = set() @property def name(self): r...
import pprint import re chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" codes = """.- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.. .---- ..--- ...-- ....- ..... -.... --... ---.. ----. -----""" dd = dict(zip(chars.lower(), codes.split())) DD = dict...
#!/usr/bin/python3 # This sample shows how to access image pixels. # # Licensed under the MIT License (MIT) # Copyright (c) 2016 Eder Perez import cv2 import sys arglist = list(sys.argv) if len(arglist) != 2: print('') print('Usage: python3 4_image_access.py IMAGE_PATH') print('') exit() path = argli...
#!/usr/bin/python3 def uppercase(str): for i in range(len(str)): j = ord(str[i]) if j > 96 and j < 123: j -= 32 print('{:c}'.format(j), end='') print()
#!/usr/bin/python3 """ Defines Square class """ from models.base import Base from models.rectangle import Rectangle class Square(Rectangle): """ Square """ def __init__(self, size, x=0, y=0, id=None): """ Args: * size (int): size * x (int): horizontal length ...
#!/usr/bin/python3 """ This module defines add_integer, a function that returns the sum of 2 integers """ def add_integer(a, b=98): """Returns sum of two numbers. - If one number is inputted, it returns the number plus 98. - Floats are converted to integers before addition. - Returns a Type Error if a...
#!/usr/bin/python3 """ defines Rectangle class """ BaseGeometry = __import__('7-base_geometry').BaseGeometry class Rectangle(BaseGeometry): """ Rectangle Args: * width (int): initializes width * height (int): initializes height Attributes: * width (int): width * height (i...
#!/usr/bin/python3 """ defines City class for MySQLdb integration """ from sqlalchemy import Column, Integer, String from sqlalchemy.sql.schema import ForeignKey from model_state import Base class City(Base): """ Representation of cities table Args: * id (int): represents id column * nam...
def listaDiff(List1,List2): l=[] for x in List1: if not x in List2: l.append(x) return l L1=[] L2=['1','2','3','4','5'] for i in range(5): L1.append(input("Inserisci valore: ")) for i in range(5): aux=input("Inserisci il valore: ") if aux!="": L2.pop(i) ...
import tkinter as tk from tkinter import ttk; win = tk.Tk(); win.title("My GUI"); #This blocks the resize window function #win.resizable(0,0); #Configuring and creating a label instance aLabel = ttk.Label(win, text="My cute Label *w*") aLabel.grid(column=0, row=0); #click event def clickMe(): global acti...
string = input("Please enter your own String : ") string2 = '' for i in string: string2 = i + string2 print("\nThe Original String = ", string) print("The Reversed String = ", string2)
#File IO with open('words_alpha.txt', 'r') as f: words = f.read().splitlines() #functions def num_words(): count = 0 for word in words: count+=1 return count def five_letter(): count = 0 for word in words: if len(word)==5: count+=1 return count ...
# Taking input from user name = input("Enter the hindi name: \n") # Checking for last vowels n = len(name) if name[n-1] in ('a', 'e', 'i', 'o', 'u'): print(name," is a woman") else: print(name," might be a man, onto the next step:") # Moving on to next classifier, sonorants # last 3 chars of th...
from sys import exit from Classes.game import bcolors, Person, Creature print("Hello and welcome to your journey, today we will go across a a forest path and we may encounter enemies.") print("Keep an eye on the hints, which will affect the story as you go along. You may be attacked at random.") print("When you enter ...
第一遍 看答案,学数据结构,学最优解 第二遍 背 第三遍 自己写 # 28. Implement strStr() def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ for i in range(len(haystack) - len(needle) + 1): if haystack[i:i + len(needle)] == needle: return i return -1 # 459....
first = 'John' last = 'Doe' street = 'Main Street' number = 123 city = 'AnyCity' state = 'AS' zipcode = '09876' print('{} {}\n{} {}\n{}, {} {}'.format(first, last, number, street, city, state, zipcode))
sentence = "Guido van Rossum heeft programmeertaal Python bedacht." for vowels in sentence: if vowels in 'aeiouAEIOU': print(vowels, end=" ") else: print("false")
Brown = {'Boxtel', 'Best', 'Beukenlaan', 'Eindhoven', 'Helmond \'t Hout', 'Helmond', 'Helmond Brouwhuis', 'Deurne'} Green = {'Boxtel', 'Best', 'Beukenlaan', 'Eindhoven','Geldrop', 'Heeze', 'Weert'} total = {'test', 'test'} def setfunc(): total.clear() samebrogre = Brown.intersection(Green) diffbrown = Brown...
tupleList = ('test', 'test', 'test2', 'test') dictList = {'test': 'test', 'test2': 'test'} setList = {'test', 'test', 'test2', 'test'} listList = ['test', 'test', 'test2', 'test'] tableList = [] print(sorted(tupleList)) print(sorted(dictList)) print(sorted(setList)) print(sorted(listList))
#/usr/bin/python3 # Author = Tom van Hamersveld - V1P - 2016 ## # Creating list which is used later on cancelList = [] ### # Open the files ## cancelFile = open('annuleringen.txt', 'r') trainStationsFile = open('treinritten.txt', 'r') resultFile = open('resultTreinritten.txt', "w") ### # Reading the lines into the vari...
numberList = [1,2,3,4,5,6,7,8,9,0] def som(numlist): res = 0 for num in numlist: res += num print(res) return res print(som(numberList))
#coding: utf-8 u""" 暗号文 与えられた文字列の各文字を,以下の仕様で変換する関数cipherを実装せよ. 英小文字ならば(219 - 文字コード)の文字に置換 その他の文字はそのまま出力 この関数を用い,英語のメッセージを暗号化・復号化せよ. """ def cipher(texts): output = "" for text in texts: if text.islower(): output += chr(219 - ord(text)) else: output += te...
# coding: utf-8 u""" ファイル参照の抽出 記事から参照されているメディアファイルをすべて抜き出せ。 """ import ch03_01 import re text = ch03_01.extract('イギリス').split('\n') pattern = r'(?:File|ファイル):(.+?)\|' for line in text: true = re.search(pattern, line) if true is not None: print(true.group(1))
def factorize_number(x): factorized_numbers = [] devisor = 2 while x > 1: if x % devisor == 0: factorized_numbers.append(devisor) x //= devisor else: devisor += 1 return factorized_numbers
def circular_shift_right(arr:list): length = len(arr) if(length < 2): return arr last = arr[length - 1] for i in range(length - 1, 0, -1): arr[i] = arr[i - 1] arr[0] = last l = [1,2,3,4,5,6] circular_shift_right(l) print(l)
#!/usr/bin/python import sys def hex_to_comma_list_valid(hex_mask): if "," in hex_mask: hex_arr = hex_mask.split(",") hex_sum = "0x0" for h in hex_arr: hex_sum = hex(int(str(hex_sum)[2:], 16)+int(h, 16)) return hex_to_comma_list(hex_sum[2:]) return hex_to_comma_list(...
from data import distances, cities def getDistance(city, otherCity): '''Returns distances between city and otherCity Require data package''' return distances[city][otherCity] def getTotalDistance(chr): '''Return the total distance from a road (list of int) Require data package''' s = 0 ...
__author__ = 'Cullin' import PatternCount def freq_words(text,kmer): max_count = 0 freq_words_dict = {} for i in range(0,len(text)-kmer + 1): word = text[i:i+kmer] freq = PatternCount.pattern_count(text,word) if freq >= max_count: max_count = freq freq_words...
#!/usr/bin/python2 import cv2 # laoding image img=cv2.imread('cat.jpg') img1=cv2.imread('cat.jpg',0) # Print height and width print img.shape # to display that image cv2.imshow("cat",img) cv2.imshow("catnew",img1) # image window holder activate cv2.waitKey(0) # waitkey will destroy by using q button...
import pandas as pd import matplotlib.pyplot as plt df=pd.read_json(r'./rain.json') print(df) print("df.statistics:",df.describe()) df.plot(x='Month',y='Temperature') df.plot(x='Month',y='Rainfall') plt.show()
#!/usr/bin/env python from BeautifulSoup import BeautifulSoup import urllib, json, string # Get the content of the page print "Fetching page from http://news.bbc.co.uk/1/hi/uk_politics/8044207.stm ..." doc = urllib.urlopen('http://news.bbc.co.uk/1/hi/uk_politics/8044207.stm').read() print "Done!" # Strip non-ASCII c...
class Customer: def __init__(self, id, x, y, zone=-1, isDepot=False): self.id = id self.x = x self.y = y self.zone = zone self.isDepot = isDepot self.isDayCustomer = False self.acceptedVehicleTypes = [] def isDummy(self): return self.id < 0 d...
''' Created on 02-Oct-2018 @author: shubham ''' class quickunion(object): def __init__(self,filepath): self.file=open(filepath,"r+") array_length=int(self.file.readline().strip("\n")) self.data=[i for i in range(array_length)] self.initialise() print self.data d...
import sqlite3 conn=sqlite3.connect('prices.db') c = conn.cursor() for row in c.execute('SELECT * FROM price'): print (row)
n = int(input("Enter the number until which you want to find the sum : ")) sumS = 0 for x in range(1,n+1): sumS += x print("The sum of first %d numbers is %d." % (n, sumS))
class MyList: def __init__(self, numbers=[1, 2, 3]): self.numbers = numbers self.output_sum = None self.output_min_max = None self.output_max_diff = None self.return_sum() self.return_min_max() self.return_max_diff() def return_sum(self): """ Fun...
import os import string import re #Files to read & variables file = open("paragraph_1.txt") text = file.read() #Count using split function words = text.split(" ") sentences = re.split("(?<=[.!?]) +", text) #print (words) #print (sentences) word_counts = len(words) sentence_counts = len(sentences) #Compute...
#assignment 1 # print hello world print ('Hello World') print("by K.Kamalakannan") #add two numbers a=10 b=25 c=a+b print(c) # find maximum a=int(input("enter numb1: ")) b=int(input("enter numb2: ")) if(a>b): print("num1 is maximum") else: print("num2 is maximum") # OR a=int(input("enter num1:")) b=int(in...
#1. create a function getting two integer inputs from user & print the following def math_funcs(num1, num2, sign): if(sign=='+'): print("Addition of two numbers :", num1+num2) elif(sign=='-'): print("Subtraction of two numbers :", num1-num2) elif(sign=='*'): print("Multiplication of ...
#Pandigital Fibonacci ends #Problem 104 #The Fibonacci sequence is defined by the recurrence relation: # Fn = Fn-1 + Fn-2, where F1 = 1 and F2 = 1. #It turns out that F541, which contains 113 digits, is the first Fibonacci #number for which the last nine digits are 1-9 pandigital (contain all the #digits 1 to 9, b...
#Largest prime factor #Problem 3 #The prime factors of 13195 are 5, 7, 13 and 29. #What is the largest prime factor of the number 600851475143 ? def primes(n): primfac = [] d = 2 while d*d <= n: while (n % d) == 0: primfac.append(d) n //= d d += 1 if n > 1: ...
import random options = ["snake", "water", "gun"] user_score = 0 Computer_score = 0 print("Please Enter any one of the following\n snake \n water \n gun") i = 1 j = 7 while i < 7: print("You have ",j, "chances left \n") Player = input("Enter Your choice: ") Computer_choice = random.choice(...
a, b = 7, 5 a = a + b b = a - b a = a - b print("After Swapping Numbers") print('a =', a) print('b =', b)
'''Project Euler Problem 102 Triangle Containment April 24, 2018''' file = "C:\\Users\\pfarrell\\Downloads\\p102_triangles.txt" with open(file) as f: nums = [] points = [] for line in f.readlines(): data = line.split(',') #tris.append(data.strip()) for p in data: ...
# # @lc app=leetcode id=53 lang=python3 # # [53] Maximum Subarray # # https://leetcode.com/problems/maximum-subarray/description/ # # algorithms # Easy (45.93%) # Likes: 7387 # Dislikes: 341 # Total Accepted: 975.8K # Total Submissions: 2.1M # Testcase Example: '[-2,1,-3,4,-1,2,1,-5,4]' # # Given an integer arra...
# # @lc app=leetcode id=20 lang=python3 # # [20] Valid Parentheses # # https://leetcode.com/problems/valid-parentheses/description/ # # algorithms # Easy (38.01%) # Likes: 4056 # Dislikes: 194 # Total Accepted: 841.2K # Total Submissions: 2.2M # Testcase Example: '"()"' # # Given a string containing just the cha...
#!/usr/bin/env python3.6 user = {"admin": True, "active": True, "name": 'Vimal'} prefix ="" if user['admin'] and user['active']: prefix="Active - Admin" elif user['admin']: prefix="Admin" elif user['active']: prefix="Active" print(f"testing the input {prefix}, {user['name']}")
import utime class Timer: def __init__(self): """Class that implements timer at microsecond clock """ self.start = utime.ticks_us() def reset(self): """Resets the timer """ self.start = utime.ticks_us() def duration(self): """Returns time elapsed si...
def menorVetor(vet): menor = vet[0] for i in range (0,5): if vet[i] < menor: menor = vet[i] return menor vetor = [] for i in range(0, 5): vetor.append(int(input('Informe um numero: '))) m = menorVetor(vetor) print(m)
notas = dict() notas2 = dict() notas = {'Ana': 9.5, 'José': 8.2, 'Maria:': 9.8, 'João': 7.9} #notas2 = {'Yuri': 9.5, 'Tiago': 8.2, 'Lucas': 9.8, 'Max': 7.9} #get # uma função do dicionario para procurar e devolver alguma coisa #print(notas.get('Carla', 'Nome não encontrado')) #utilizando in #ele traz o valor de true ...
numero = int(input('Digite um numero: ')); fatorial = 1 while numero > 0: fatorial *= numero numero -= 1 print(fatorial)
# 04-02. FUNCTIONS [Exercise] # 06. Password Validator def valid_pass(string): valid_password = True if not 6 <= len(string) <= 10: valid_password = False print('Password must be between 6 and 10 characters') for char in string: if not (char.isalpha() or char.isnumeric()): ...
# 04-02. FUNCTIONS [Exercise] # 04. Odd and Even Sum def odd_even_sum(string): odd_sum = 0 even_sum = 0 for char in string: num = int(char) if num % 2 == 0: even_sum += num else: odd_sum += num print(f'Odd sum = {odd_sum}, Even sum = {even_sum}') odd_ev...
# 08-02. TEXT PROCESSING [Exercise] # 04. Caesar Cipher text = input() encrypted_text = '' for char in text: encrypted_text += chr(ord(char) + 3) print(encrypted_text)
# 03-02. LISTS BASICS [Exercise] # 10. Bread Factory energy = 100 coins = 100 managed = True events = input().split('|') for event in events: event_type, number = event.split('-') number = int(number) if event_type == 'rest': if energy < 100: gain = min(number, 100 - energy) ...
# 08-02. TEXT PROCESSING [Exercise] # 01. Valid Usernames usernames = input().split(', ') for username in usernames: is_valid = True if 3 <= len(username) <= 16: if len(username) == len(username.strip()): for char in username: if char.isalpha() or char.isdigit() or char in ...
# 03-02. LISTS BASICS [Exercise] # 05. Faro Shuffle string = list(input().split(' ')) shuffles = int(input()) half = int(len(string) / 2) for i in range(shuffles): string1 = string[0:half] string2 = string[half:] string = [] for j in range(half): string.extend([string1[j], string2[j]]) print...
# 08-02. TEXT PROCESSING [Exercise] # 03. Extract File path = input() file_name_start = path.rfind('\\') + 1 file_name_end = path.rfind('.') file_name = path[file_name_start:file_name_end] file_extension = path[file_name_end+1:] print(f'File name: {file_name}') print(f'File extension: {file_extension}')
# 05-01. LISTS ADVANCED [Lab] # 04. Even Numbers integers = input().split(', ') integers = list(map(int, integers)) integers_even = [] for i, val in enumerate(integers): if val % 2 == 0: integers_even.append(i) print(integers_even)
# 09-03. REGEX [More Exercises] # 01. Race import re participants = input().split(', ') race = {} for p in participants: race[p] = 0 while True: string = input() if string == 'end of race': break name = '' letters = re.findall('[A-Za-z]', string) for l in letters: name += l ...
# 06-01. OBJECTS AND CLASSES [Lab] # 05. Circle class Circle: __pi = 3.14 def __init__(self, diameter): self.diameter = diameter self.radius = diameter / 2 def calculate_circumference(self): return Circle.__pi * self.diameter def calculate_area(self): return Circle.__...
# 07-01. OBJECTS AND CLASSES [Lab] # 02. Stock stock = {} items = input().split(' ') for i in range(0, len(items), 2): key = items[i] value = items[i+1] stock[key] = int(value) search = input().split(' ') for i in search: if i in stock.keys(): print(f'We have {stock[i]} of {i} left') else...
# 04-02. FUNCTIONS [Exercise] # 01. Smallest of Three Numbers def min_of_three(num1, num2, num3): return min(num1, num2, num3) a = int(input()) b = int(input()) c = int(input()) print(min_of_three(a, b, c))
# 04-01. FUNCTIONS [Lab] # 04. Orders def total(product, quantity): if product == 'coffee': return 1.50 * quantity elif product == 'water': return 1.00 * quantity elif product == 'coke': return 1.40 * quantity elif product == 'snacks': return 2.00 * quantity order_prod...
# 07-02. OBJECTS AND CLASSES [Exercise] # 09. ForceBook forcebook = {} while True: command = input() if command == 'Lumpawaroo': break if ' | ' in command: side, user = command.split(' | ') all_users = [] for users in forcebook.values(): all_users += users ...
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
# ---------------------------------------------------+ # Projectiles are fired when someone (player or # villain) fires a shot with a gun. # A projectile is basically a moving item. # ---------------------------------------------------+ import math import pygame from Functions import getMovingVector class Projectil...
'''A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers.''' from math import ceil first_num=100 max_product=0 def palindrome_checker(num): s=str(num) first_fr...
class CodingProblem2: def __init__(self,list): self.list = list; def computeUsingOptimalSolution(self): suffix_products = [] # Generate list of products suffix of element i for num in reversed(self.list): if suffix_products: suffix_products.append(suffix_products[-1] * num) # Multiply each element by las...
# A website requires users to enter a username and password to register. Write a program to check the validity of the password entered by the user. # Password check criteria include: # 1. At least 1 letter is in [a-z] # 2. At least 1 number is in [0-9] # 3. At least 1 character in [A-Z] # 4. At least 1 character inside...
# Write a program that accepts a string of words entered by the user, separated by commas, and prints the words in alphabetical order, separated by commas. # Input is: without,hello,bag,world, the output will be: bag,hello,without,world. items = [i for i in input().split(',')] items.sort() print(','.join(items))
#defining a function def simpleFunction(): print ("Simple funcion") print ("Does nothing") def addThis(x, y): print (x+y) return x+y #calling funcions simpleFunction() x = 6 print (x) x = simpleFunction x() a = addThis(2,3) addThis(2.7,3.14) addThis("Add"," This?")
#comment: Single line comment #==== # Part-1 #==== a = 5 print (a) a = "Allowed?" print (a) a, b, c = 1, 15, 9 print (b) print (c) a, b = 5, "Other than number" a, b = b, a print (a) print (b) x = input ("Enter a number: ") x = int (x) x = x + 1 print (x) #==== # if-else #==== if x > 0 and x < 100: print ("x...
l1 = [1, 2, 3, 4, 5, 6] ex1 = [variavel for variavel in l1] ex2 = [v * 2 for v in l1] ex3 = [(v, v2) for v in l1 for v2 in range(3)] print(ex1) print(ex2)
# we've keys and value # in list, python create the index for us # in dictionary, keys are unique, we cannot duplicate it d1 = {'car': 'mitsubishi', 'brand': ''} d1['nova chave'] = 'new value' print(d1) print(d1['nova chave']) d2 = dict(chave1='valor da chave') print(d2) print('*****************') d3 = {1: 'key', ...
import sqlite3 conexao = sqlite3.connect('basededados.db') cursor = conexao.cursor() cursor.execute('CREATE TABLE IF NOT EXISTS clientes (' 'id INTEGER PRIMARY KEY AUTOINCREMENT,' 'nome TEXT,' 'peso REAL' ')' ) #cursor.execute('INSERT INTO cl...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 22 22:15:10 2020 @author: gabrielguimaraes """ numero = 2 print(numero) vetor = [2,3,4] import numpy as np vetor = np.asarray(vetor) print("maior valor", vetor.max()) print("posicao de maior valor", vetor.argmax()) print("valor minimo", veto...
user = input("Create your user ") password = input("Create your password") qtd = len(user) print(user, qtd) if len(password) < 5: print("Short Password") else: print("ok")
def daysPerMonth(year, month): # Days per month is statis for all months except February if(month in [1,3,5,7,8,10,12]): return(31) elif(month in [4,6,9,11]): return(30) else: # Days per month in February will vary depending upon leap year # Every 400 years is...
class DiophanticSum: def __init__(self, coefficients, constant): assert all([type(c) is int for c in coefficients.values()]) assert type(constant) is int self.coefficients = coefficients self.constant = constant def getConstant(self): return self.constant def getCoeff...
def InsSort(arr, start, end): for i in range(start + 1, end + 1): elem = arr[i] j = i - 1 while j >= start and elem < arr[j]: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = elem return arr def merge(arr, start, mid, end): if mid == end: return arr ...
# -*- coding: utf-8 -*- """The module that initializes a CSV file This module is needed to create a CSV file with random records via Faker """ from faker import Faker import csv def init_csv_file(source): """The function that initializes a CSV file Args: source (Faker()): the source of random name...
import math def sum_digits(number): # number_str = str(number) # summa = 0 # for digit in number_str: # summa += int(digit) # return summa s = 0 while number: s += number % 10 number //= 10 return s def find_result(number): step = 9 if number % 3 == 0: ...
def reverse(text): return text[::-1] def is_palinrome(text): return text == reverse(text) something = input('Введите текст: ') something = something.lower() forbidden = ('.','?','!',':',';','-','—',' ',) for i in something: if i in forbidden: something = something.replace(i, '') if(is_palinrome...
def solveMeFirst(a,b): return a+b num1=int(raw_input("Enter The First No")) num2=int(raw_input("Enter The Second No")) res=solveMeFirst(num1,num2) print(res)
import os import json print("Enter the absolute file path to the directory you need filenames for...") print("(Ex: 'C:\Users\Vincent\Desktop')") filenamesPath = input("Enter path: ") print("Enter the absolute file path to the directory where you want the text file to be generated...") outputPath = os.path.join(input("...
import tkinter win = tkinter.Tk() win.title("jakccsm") win.geometry("400x300+200+200") scroll = tkinter.Scrollbar() text = tkinter.Text(win,width=200,height=2) scroll.pack(side=tkinter.RIGHT,fill=tkinter.Y) text.pack(side=tkinter.LEFT,fill=tkinter.Y) scroll.config(command=text.yview) text.config(yscrollcommand=scr...
#!/usr/bin/env python3 #! -*- coding: utf-8 -*- class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ length = len(nums) index = 0 count = 0 while count < ...