text
stringlengths
37
1.41M
class Queen: def __init__(self, row, column): if row < 0 or row > 7 or column < 0 or column > 7: raise ValueError(r".+") self.row = row self.col = column def can_attack(self, another_queen): if self.row == another_queen.row and self.col == another_queen.col: ...
def is_isogram(string): count = [0] * 26 for c in filter(lambda c: c.isalpha(), string.lower()): count[ord(c) - 97] += 1 return all(map(lambda x: x < 2, count))
def classify(number): if number < 1: raise ValueError(r".+") i = 1 aliquot_sum = 0 while i * i < number: if number % i == 0: aliquot_sum += i + number // i i += 1 if i * i == number: aliquot_sum += i if aliquot_sum - number == number: retu...
def response(hey_bob): question = hey_bob.rstrip().endswith('?') yell = any(c.isupper() for c in hey_bob) \ and not any(c.islower() for c in hey_bob) nothing = not hey_bob.strip() if question and not yell: return "Sure." elif not question and yell: return "Whoa, chill out!" ...
import re import sys from argparse import ArgumentParser #import the ArgumentParser object from this module, allows for more than one argument into command line import os def parse_for_terms_and_dir(): argparser = ArgumentParser() #creates a parser object argparser.add_argument('--search','-s', dest='search', ...
# -*- coding: utf-8 -*- """ Created on Sat Dec 8 16:41:48 2018 @author: Cecilie """ import numpy as np import math as m def g_Incline(a,t,d,d_rail,D_ball,theta,Delta_theta,sigma_t,sigma_d,sigma_rail,sigma_ball,sigma_theta): """ Computes the error on gravitational acceleration g for a 'Ball Incline Exper...
# this program reads the contents of the # philosophers.txt file one line at a time def main(): # open a file named philosohpers.txt infile = open( 'philosophers.txt', 'r' ) # read three lines from the file. line1 = infile.readline() line2 = infile.readline() line3 = infile.readline() # cl...
def process_input(file_name): incompatibilities = {} washing_times = {} with open(file_name) as file: for line in file: line = line.rstrip("\n") data = line.split() first_character = data[0] if first_character == 'c': continue elif first_character == 'e': if data[1] not...
moves = [] direction = "" path = {"E":0,"S":0,"W":0,"N":0} amount = 0 with open ('YourFile_Puzzle12.txt') as f: for line in f: line = line.rstrip("\n") direction = line[0] amount = line[1:] moves.append((direction,amount)) """ First part of the exercies """ # current_direction = "...
from enum import auto, Enum #enum okundu # Tuple'larda keyler integer olarak tanımlanır. Enum burda bunun önüne geçer bir bakıma ve bize sembolik isimleri # değerler için atamamıza olanak tanır. from itertools import product """ #itertools -> product cartesian product, equivalent to a nested for-loop ex -> product('A...
from math import sqrt, acos, pi class Vector(): """Represents a Vector.""" def __init__(self, coordinates): try: if not coordinates: raise ValueError self.coordinates = coordinates self.dimension = len(self.coordinates) except ValueError: raise ValueError('The coordinates must not be empty')...
''' CD: change directory ls: look for stuff (shows you files in that directory in case you forgot/don't know what you're looking for) ls -al: looking for even hidden files; Topher doesn't have any Hidden files denoted with a . in front of file name eg .WoWDude vocab: Direc directory...? its the files and bits...
#!/usr/bin/env python import sys count = 0 previousKey = None for line in sys.stdin: currentKey, currentValue = line.strip().split() if(currentKey == previousKey): count += f"{currentValue} " else: print(f"{previousKey} {count}") count = f"{currentValue} " previousKey = ...
a = int(input("Enter the number of hellos you need to fuck off")) i=0 for i in range ( a): print("HELLO THERE") print("General Kenobi") print("You are a bold one")
#!/usr/bin/env python import sys # input comes from STDIN (standard input) for line in sys.stdin: line = line.strip() line = line.replace('\"','') words = line.split(',') temp = words[21] try: temp = float(temp) temp = (temp - 32) * 0.5556#to celcious if temp<-15: print '%s\t%s' % ("Below -15 Celsius", 1...
from datetime import datetime def product_element_1(n): return (2*n) / (2*n - 1) def product_element_2(n): return (2*n) / (2*n + 1) def product_element(n): return product_element_1(n) * product_element_2(n) def approximation_of_pi(): n = 1 prior = 1 current = 1 change = True while change: prior = current ...
# -*- coding: utf-8 -*- from utils.proj_eul_math import combinatorics NUM_DIGITS = 10 def run_problem(place_of_permutation=1000000): curr_digit = NUM_DIGITS curr_place = place_of_permutation - 1 digits = [ x for x in range(NUM_DIGITS) ] ordered_digits = [] while curr_digit > 0...
# -*- coding: utf-8 -*- import collections starting_set = set() for x in range(1, 101): starting_set.add(x * x) STARTING_SET = frozenset(starting_set) def run_problem(S=starting_set, k=50): cache = [] for _ in range(k + 1): cache.append(dict()) # To make updating the cache easier, we invert t...
# -*- coding: utf-8 -*- from utils.proj_eul_math import general def get_hexagonal(n): return n * (2 * n - 1) def run_problem(): # 143 is a hexagonal number curr_index = 144 while True: hexagonal_number = get_hexagonal(curr_index) # All triangular numbers are hexagonal, so we don't need to check. i...
# -*- coding: utf-8 -*- import requests from utils.proj_eul_math import general WORDS_URL = 'https://projecteuler.net/project/resources/p042_words.txt' def _score_word(word): total = 0 for c in word: total += ord(c) - ord('A') + 1 return total de...
# -*- coding: utf-8 -*- from utils.proj_eul_math import prime def run_problem(max_value=2000000): total = 0 for p in prime.get_primes(max_num_inclusive=max_value): total += p return total if __name__ == '__main__': answer = run_problem(max_value=10) if answer == 17: print('Correc...
# -*- coding: utf-8 -*- # TODO: Rewrite combinatorically a + b - (a \and b) def run_problem(n=1000, multiple_set={3, 5}): total = 0 for num in range(n): if any_divides(num=num, multiple_set=multiple_set): total += num return total def any_divides(num, multiple_set): for x in mult...
# -*- coding: utf-8 -*- from __future__ import division def run_problem(n=1001): n = int(n / 2) return int((16 * n**3 + 30 * n**2 + 26 * n + 3) / 3) if __name__ == '__main__': answer = run_problem(n=5) # TODO if answer == 101: print('Correct!') else: print('Incorrect!')
""" Создать программный файл в текстовом формате, записать в него построчно данные, вводимые пользователем. Об окончании ввода данных будет свидетельствовать пустая строка. """ file = open("test_file", "w") # Откроем ткстовый файл для записи" line = input("Введите текст \n") while line: file.writelines(line) l...
a = input("Введите элементы списка через пробел a=: ").split() for i in range(0,len(a),2): a[i:i+2]=a[i:i+2][::-1] print(a)
""" Пользователь вводит целое положительное число. Найдите самую большую цифру в числе. Для решения используйте цикл while и арифметические операции. Возвращает большую цифру числа Вводится целое положительное число Приваиваем значению b остаток деления на 10 этого числа, который является последней его цифрой делим ...
# ein "Dictionary" oder deutsch "Verzeichnis" ist sehr schnell, verwaltet Listen oder einträge zu eine "Schlagwort", # es benötigt immer. dir ={key:value} schlüsselwert:inhaltswert # erklärung im video: https://youtu.be/uZsFGyhsPLE?t=880 print() print("Wir spielen etwas mit listen und verzeichnisen herrum....
#!/usr/bin/env python3 import sys data = open(sys.argv[1]).read() # the above is a shortened form of: # infile = open(sys.argv[1]) # data = infile.read() # sys.argv, sys.stdin, sys.stdout, sys.stderr chars = len(data) words = len(data.split()) # split on strings lines = len(data.split('\n')) print("{0} {1} {...
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def flatten(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place...
#!/usr/bin/python #FileName:using_tuple.py zoo = ('wolf', 'elephant', 'pengui') print 'Number of animals in the zoo is', len(zoo) #output 3 new_zoo = ('monkey', 'dolphin', zoo) print 'Number of animals in the new zoo is', len(new_zoo) #output 3, the third elem is still a tuple print 'All animals in new zoo are', n...
#!/usr/bin/python #FileName:using_dict.py # 'ab' is short for address book ab = { 'Swaroop':'Swaroop@alibaba-inc.com', 'Larry':'larry@alibaba-inc.com', 'Matsumoto':'matz@alibaba-inc.com', 'Spammer':'spammer@alibaba-inc.com' } print "Swaroop's address is %s" %ab['Swaroop'] #Adding a key/value pair ab['...
# Author: Stanley Calixte # Project: Project 1 - Movie Trailer Website class Movie(): """ A class property providing information about a movie. Attributes: title: [String], the title of the movie. ating: [String], the rating of the movie. year: [Integer], the year the movie was released. info: [String], a short d...
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. def read_file(file_name): with open(file_name, "r") as f: input = [x.strip() for x in f.readlines()] return...
# Implement Selection Sort import time # we have a data set starting with the very basic happy path to complex data = { "data1" : [5,4,1,3,2], # happy path easy to vizualize "data2" : [5,4,1999,3,2,8,7,6,10,100], #larger range of values "data3" : [5,4,1,3,2,2], # repeated values "data4"...
# Problem Description # Given an integer array A of size N. # You can pick B elements from either left or right end of the array A to get maximum sum. # Find and return this maximum possible sum. # NOTE: Suppose B = 4 and array A contains 10 elements then: # You can pick first four elements or can pick last four elemen...
#!/usr/bin/env python3 # example workign with conditionals #By Sam on 10/10/21 number = int(input("Choose a number between 1 and 4: ")) if number == 1: print("Wrong number, try again") print("Another example") elif number == 2: print("Wrong number, try again") elif number == 3: print("Corr...
#!/usr/bin/env python3 # A simple "Hello World" script in python with Inputs # Created by Ed Goad, 2/3/2021 your_name = input("What is your name? ") print("Hello {0}".format(your_name)) print(f"Hello {your_name}") print("Hello " + your_name) print("Hello", your_name) message = "Hello" + " " + your_name print...
#!/usr/bin/env python3 # A simple calculator to show math and conditionals # Created by Sam on 10/1/21 # Get information from user first_number = float( input("What is the first number? ") ) activity = input("What activity? ( + - * / ) ") second_number = float( input("What is the second number? ") ) # Do mat...
#!/usr/bin/env python3 # A simple calculator to show math and conditionals # Created by Ed Goad, 2/3/2021 # Get inputs first # Note we are casting the numbers as "float", we could also do "int" first_num = float(input("What is the first number: ")) activity = input("What activity? ( + - * / ) ") second_num = f...
#!/usr/bin/env python3 # Script that "encrypts"/"decrypts" text using base64 encoding # By Ed Goad # 2/5/2021 # import necessary Python modules import base64 def encode_data(plain_text): # Convert plain_text string to bytes plain_text = plain_text.encode() # Encode the plain_text cipher_te...
from queue import Queue """ Simple graph implementation """ class Graph: """Represent a graph as a dictionary of vertices mapping labels to edges.""" def __init__(self): self.vertices = {} def add_vertex(self, vertex): self.vertices[vertex] = set() def add_edge(self, vertex1, vertex...
import heapq import os class Node: def __init__(self, frequency,value): self.left = None self.right = None self.frequency = frequency self.value = value def __lt__(self, other): if other is None: return -1 else: return self.frequency < o...
class User(): """creates a class about a user""" def __init__(self,first_name,last_name,age,gender): """initializes description of a user""" self.fname = first_name self.lname = last_name self.age = age self.gender = gender def describe_user(self): print(f"M...
x=int(input("determiner un nombre")) y=int(input("determiner un nombre")) m=int((x+y)/2) print("la moyenne est de "+str(m))
numbers=[10,20,30,40] # numbers.append() # numbers.insert() # numbers.reverse() # numbers.sort() # numbers.remove() # numbers.pop() print(numbers)
import numpy as np import matplotlib.pyplot as plt from api.static.visualization import draw_neural_net from models.ml.visualization.neural_network import NeuralNetworkDrawer import sklearn.metrics as metrics np.random.seed(100) ''' HOW TO USE: Python nn = NeuralNetwork() nn.add_layer(Layer(2, 3, 'tanh')) nn.add_laye...
Python 3.4.0 (default, Jun 19 2015, 14:18:46) [GCC 4.8.2] on linux Type "copyright", "credits" or "license()" for more information. >>> import random question = input("Welcome to the\nMAGIC EIGHT BALL!\nPress enter for answer") x = random.randint(1,20) answers_dict = { 1:"Yes", 2:"No", 3:"Maybe", 4:"Al...
import csv #use another path #file = open(faktura.csv) file = open('finanse_i_obiektowosc/faktura.csv', encoding='UTF8') output = open('finanse_i_obiektowosc/output.csv', 'w', newline='', encoding='UTF8') csvreader = csv.reader(file, delimiter=";") writer = csv.writer(output) header = ["NAZWA PRODUKTU","CENA NETTO"...
# -*- coding: utf-8; -*- class ScoreCalculator(object): @staticmethod def get_best_scores(runs): num_successful = 0 for run in runs: if not run['failed_trial']: num_successful += 1 l1_scores = [run['score'] for run in runs if run['level'] == 1] l2_s...
#!/usr/bin/python3 from functools import reduce def init() -> tuple[int, int, int]: """ Вводимо початкові дані. """ a = int(input("Введіть a: ")) b = int(input("Введіть b: ")) c = int(input("Введіть c: ")) return a, b, c def gcd(*numbers: int) -> int: """ Знаходить найбільше...
#!/usr/bin/python shoplist = ['apple','mango','carrot','banan'] print 'Item 0 is', shoplist[0] print 'Item -1 is', shoplist[-1] name = 'swaroop' print 'characters 1 to 3 is', name[1:3]
""" first line opens the data file second line creates the averages file for final output """ datafile = open('data.txt', 'r') average = open('averages.txt', 'w') """ a for loop that reads returns each item in the text file as a list... the split function splits each item in the list so that the program kn...
print("input 5 decimals") values = [] for i in range(5): values.append(float(input("demical #"+str(i+1)+": "))) cnt = 0 for i in values: if i >= 10 and i <= 100: cnt += 1 print(cnt)
#!/usr/bin/python # coding: utf-8 # 自然数1から100までをそれぞれ二乗したものの合計と、全てを合計を二乗したものの差を求めます。 def q6(): sum_of_squares = 0 # それぞれの二乗の合計 square_of_sum = 0 # 全ての合計の二乗 # 1から100までの自然数の二乗を加えていきます。 for n in range(1, 101): sum_of_squares += n * n # 1から100までの自然数を加えていきます。 for n in range(1, 101): ...
#!/usr/bin/python # coding: utf-8 NUMBERS = {'0': '', '1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine', '10': 'ten', '11': 'eleven', '12': 'twelve', '13': 'thirteen', '14': 'fourteen', '15': 'fifteen', '16': 'sixteen', '17': 'seven...
#함수 #def 함수명(변수(생략가능)): def myFun(): print('Hello python') myFun() def myFun2(str): print(str) myFun2("Hello python2") myFun2("Hello JAVA") myFun2("Hello nexacro") def myFun3(var1, var2): for i in range(var2): print('{1} 번째 {0}'.format(var1, i)) myFun3("Hello python", 5) def myFun4(var1, var...
# Task : Print the FizzBuzz numbers. # FizzBuzz is a famous code challenge used in interviews to test basic programming # skills. It's time to write your own implementation. # Print numbers from 1 to 100 inclusively following these instructions: # if a number is multiple of 3, print "Fizz" instead of this number, # i...
# Task: # Find out if a given year is a "leap" year. # In the Gregorian calendar, three criteria must be taken into account to identify leap years: # The year must be evenly divisible by 4; # If the year can also be evenly divided by 100, it is not a leap year; unless... # The year is also evenly divisible by 400. Th...
# Task-1: # Write a short Python program that asks the user to enter Celsius temperature # (it can be a decimal number), converts the entered temperature into Fahrenheit degree # and prints the result. # Task-2: # Write a short Python program that asks the user to enter a distance # (it can be a decimal number) in ...
# Task : Write a program that takes a number from the user and prints the result to check if it is a prime # number. num = int(input('Enter a number : ')) i = 2 if num == 2: status = f'{num} is a prime number' elif num < 2: status = f'{num} is not a prime number' else: while num % i != 0 and i < num: ...
from tkinter import * window = Tk() window.title('Mile to kilometers converter') window.config(padx=5, pady=5) # functions def miles_to_km(): result = float(miles_entry.get()) * 1.60934 kilo_label_output['text'] = '{:.2f}'.format(result) # label equal_to_label = Label(text='is equal to') equal_to_label.gr...
#def def sayHello(name,age): print("hello "+name+",your age:"+str(age)) sayHello("SanDuo",1) lFriend = ["yiduo","erduo","sanduo"] lAge = [1,2,3,4] sayHello(lFriend[1],lAge[1]) #return def nDouble_Nmuber(num): return num*2 print(nDouble_Nmuber(5)) #loqical operators:and/or/and not bIs_Good_Singer = False ...
a=int(input('Adj egy számot! ')) b=int(input('Adj egy másik számot! ')) if a==b: print('A kétszám engyelő') elif a<b: print(f'A nagyobb érték {b}.') else: print(f'A nagyobb érték {a}')
l1 = [0,1,2,3] l2 = [2,3,4,5] lst = l1 + l2 lst.sort() lng = len(lst) if(lng % 2 == 0): median = (lst[lng//2 - 1] + lst[lng//2]) / 2 else: median = lst[lng//2] print(median)
print("welcome to the triangle checker") angle1=int(input("enter the first angle")) angle2=int(input("enter the second angle")) angle3=int(input("enter the third angle")) if(angle1==60)and (angle2==60)and(angle3==60) print("a triangle with angles"angle1,","angle2," "and",angle3,"forms as an equilateral triangle") e...
# import sys # sys.path.append("../doubly_linked_list") # import doubly_linked_list from from doubly_linked_list import DoublyLinkedList """ A stack is a data structure whose primary purpose is to store and return elements in Last In First Out order. 1. Implement the Stack class using an array as the underlying stor...
def celsius_Fahrenheit(): """ Faça um Programa que peça a temperatura em graus Fahrenheit, transforme e mostre a temperatura em graus Celsius. C = 5 * ((F-32) / 9). 1 - Pedir a temperatura em Fahrenheit 2 - Aplicar a fórmula para transformar em Celsius 3 - retornar o valor de Celsius 4 - Chamar...
def fah_celsius(): """ Faça um Programa que peça a temperatura em graus Celsius, transforme e mostre em graus Fahrenheit C = 5 * ((F-32) / 9) (C × 9/5) + 32 = 35,6 °F 1 - Peça a temperatura em graus Celsius 2 - transformar em Fahrenheit 3 - retornar o Fahrenheit para a função 4 - Chamar ...
import sqlite3, config import datetime, calendar, random def calculatePrices(): # Calculate the date of today today = str(datetime.date.today()) conn = sqlite3.connect(config.DATABASE_PATH) db = conn.cursor() stock_ids = db.execute("SELECT id FROM stocks").fetchall() for id in...
def solution(priorities, location): ret = location while True: for i in range(len(priorities)): # target job if i == location: # print if priorities[i] >= max(priorities[:i] + priorities[i+1:]): return ret + 1 # ...
class Node(): def __init__(self, char): self.char = char self.children = {} self.word_finished = False # last letter of the word self.freq = 1 ''' Set word_finished to given Boolean value ''' def set_word(self, Bool): self.word_finished = Bool class Trie(): ...
def solution(array, commands): answer = [] for command in commands: i = command[0] j = command[1] k = command[2] arr = array[i-1 : j] arr.sort() answer.append(arr[k-1]) return answer if __name__ == "__main__": array = [1, 5, 2, 6, 3, 7, 4] comman...
""" This progam takes a look into a simple gen_alg model to optimize the set of 5 numbers which gives a total sum of 200""" from random import randint,random from operator import add 'Building an individual' def individual(length,min,max): 'Create a member of the population' return [ randint(min,max) for x in xra...
# Sum square difference # Problem 6 # Find the difference between the sum of the squares of the first one hundred natural numbers # and the square of the sum def sum_of_squares (first_number, last_number): total = 0 for number in range (first_number, last_number + 1): total += (number**2) return ...
class car(object): def __init__(self, price, speed, fuel, mileage): self.price = price self.speed = speed self.fuel = fuel self.mileage = mileage if self.price > 10000: self.tax = 0.15 else: self.tax = 0.12 self.display_all() def d...
#!/usr/bin/env python2 # coding=utf-8 ''' Computational Geometry Assignments | (c) 2015 Pablo Cabeza & Diego González license: [modified BSD](http://opensource.org/licenses/BSD-3-Clause) ''' import numpy as np def andrews_hull(pts): ''' Compute the convex hull using andrews hull algorithm. The algorith...
import Board.Cell as cell import Board.Pieces as p class Board: # Create a map of empty cells def __init__(self): self.rows = ['8', '7', '6', '5', '4', '3', '2', '1'] self.cols = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] self.Cells = {} for i in range(0, 8): for j i...
import convertmatauang def main(): print("Convert dari Euro Ke Rupiah") a = int(input ("Masukkan nilai Euro: ")) hasil = convertmatauang.EuroKeRupiah (a) print("Hasil dari Convert Euro Ke Rupiah adalah: ", hasil, "Rupiah") print("Convert dari Dollar Ke Rupiah") b = int(input("Masukkan nilai ...
from tkinter import * # OpenFileDialog --Opens a window that allows you to select the desired file. It uses the TK module to do so. # returns a list with the data selected def OpenFileDialog(): from tkinter import filedialog windowMain = Tk() windowMain.withdraw() fileName = list(filedia...
""" Model of a train. """ import numpy as np from scipy.constants import g from math import fabs class SystemState(object): """ Class to store both train and brake state. """ def __init__(self, train_state, brake_state): self.train_state = train_state self.brake_sta...
#!/usr/bin/env python # coding: utf-8 # In[14]: #Day3 Assignment -shweta anand # In[3]: #question 1 # In[13]: #print Sum of n number using while loop # In[12]: Num=3 if Num < 0: print("Enter the digit greater than Zero") else: Sum=0 while (Num > 0): Sum=Sum+Num Num=Num-1 ...
# This works OK class SequenceGenerator: _instance = None def __new__(cls): if cls._instance is None: print('No instance exists. Creating a new one') cls._instance = super(SequenceGenerator,cls).__new__(cls) cls.sequence = 1 else: prin...
class Shape: def __init__(self,shape_type): self.__shape_type = shape_type def get_type(self): return self.__shape_type def get_area(self): pass class Rectangle(Shape): def __init__(self,width,height): self.__width = width self.__height = height def get_are...
import grader ''' Week 2: Programming Assignment 1 Store the concatenated message into the variable named "combined_message" using the two provided variables "name" and "message". ''' name = "Sean" message = " is an instructor of Intro to Python!" combined_message = name + message # Modify this line only # You c...
filename = 'pi_million_digits.txt' with open(filename) as file_object: lines = file_object.readlines() pi_string = '' for line in lines: pi_string += line.rstrip() birthday = input("Enter your birthday in the form of mmddyy: ") if birthday in pi_string: print("Your birthday is present on the file") else:...
#Condition in python (Statement) a = 3 b = 21 if a % b == 0: print("a is divisable by b") elif b + 1 == 22: print("B is incremented and the result is 22") else: print("its the end of the statement")
#10.1 filename ='learning_python.txt' with open(filename) as file_object: lines = file_object.readlines() string = '' for line in lines: string += line.rstrip() print(string) print(len(string))
alien_color = ['green', 'red', 'yellow'] print(alien_color) alien = 'green' #methods if alien is 'green': print('You just earned 5 points') else: print('You just earned 10 points') # alien = 'red' if alien is 'green': print('You just earned 5 points') elif alien is 'yellow': print('you just earned 1...
class Users(): def __init__(self, first_name, last_name, location, age,): self.first_name = first_name self.last_name = last_name self.location = location self.age = age self.full_name = first_name + ' ' + last_name self.login_attempts = 0 def describe_user(self)...
print('The addition of a and b is' , 5 + 3) #add print("The subraction of ", 10 - 2) #sub print("The Multiplication of ", 2 * 4) #Mul print("The division of ", 80 / 9) #Div a = 3 message = "This is my favorite number " + str(a) print(message)
def get_formatted_name(first_name, last_name): """Display the name of the person""" full_name = first_name + ' ' + last_name return full_name.title() #“When you call a function that returns a value, you need to provide a variable where the return value can be stored. In this case, the returned value is stor...
#more printing print("Mary had a little lamb") print("Its fleence was white as {}.".format('snow')) #This is another way to use format here we can assign the snow inside the format print print("And everywhat that mary went.") print("." * 5) #what would that do #it will print 15 - after the last print statement end1 =...
# python convertion to demonstrate type convertion # # to convert ord(), hex(), oct() # initializing integer s = '4' c = ord(s) print("after converting character into integer is :", end= ' ') print(c) h = hex(56) print("after converting 56 to hexa decimal is : ", end = '') print(h) o = oct(56) print("After conv...
filename = 'programming.txt' with open(filename, 'W') as file_object: #“You can open a file in read mode ('r'), write mode ('w'), append mode ('a'), or a mode that allows you to read and write to the file ('r+'). #If you omit the mode argument, Python opens the file in read-only mode by default.” file_object.write...
# 4.10 colors = ['blue', 'green', 'gray', 'black', 'white', 'red', 'yellow'] print("The first three items in the list are: ") print(colors[0:3]) print("The three items in the middle of the list are: ") print(colors[2:5]) print("The last three in the list are: ") print(colors[-3:]) # 4.11 My pizza your pizzas pizza...
filename = 'alice.txt' try: with open(filename) as file_object: contents = file_object.read() except FileNotFoundError: msg = "The file you searching is not found" print(msg) else: words = contents.split() num_words = len(words) print("The file " + filename + " has " + str(num_words) ...
unconfirmed = ['chris', 'bob', 'david', 'sam'] confirmed = [] while unconfirmed: current_user = unconfirmed.pop() print("Verifying users: " + current_user.title()) confirmed.append(current_user) print('The following users have been confirmed: ') for confirm in confirmed: print(confirm.title())
cars = 100 space_in_cars = 4.0 drivers = 30 passengers = 90 cars_not_driven = cars - drivers cars_driven = drivers car_pool_capacity = space_in_cars * cars_driven average_person_per_car = passengers / cars_driven print("There are", cars, "cars availabe") print("There are only", drivers, "total drivers are available") ...
# cities = ['Tashkent', 'Bukhara', 'Samarkand', 'Khorezm', 'Fergana', 'Karshi', 'Nukus', 'Termz', 'Namangan', 'Andijan'] # three_cities = cities[3:6] # print(three_cities) # print(three_cities) # v obratnom poryadke # reversed_cities = cities[::-1] #gorod est li v strake true/false with help 'in' tak j i ciframi # ...
from collections import defaultdict from math import sqrt, sin, cos, tan def read_line(file): """ Helper function to read a file line by line and return list of lines. """ with open(file) as opened: lines = opened.readlines() return lines def convert_grammar(grammar_file): """ ...