text
stringlengths
37
1.41M
# Simple Hangman game with python # Author: Roxana Haghgoo import random HANGMANPICS = [''' +---+ | | | | | | =========''', ''' +---+ | | O | | | | =========''', ''' +---+ | | O | ...
#-*-coding:utf-8-*- import base64 import sys def main(): clear_text = sys.argv[2] if (sys.argv[1] == "enbase64"): print(str(base64.b64encode(clear_text.encode("utf-8")),'utf-8')) elif (sys.argv[1] == "enbase32"): print(str(base64.b32encode(clear_text.encode("utf-8")),'utf-8')) elif (sy...
too = int(input("too: ")) for i in range(1, too+1): txt = str(i)[::-1] if i == int(txt): print(txt)
#!/usr/bin/env python # coding: utf-8 # In[1]: # Write a Python program to add, subtract, multiple and divide two Pandas Series. import pandas as pd ds1 = pd.Series([2, 4, 6, 8, 10]) ds2 = pd.Series([1,3,5,7,9]) ds = ds1 + ds2 print("Add two Series:") print(ds) print("Subtract two Series:") ds = ds1 - ds2 print(ds)...
from turingmachine.types import Direction class Head: """ Represents the head of a Turing machine """ def __init__(self): """ Initialises the head at the starting position """ self.position = 0 def move(self, direction: Direction) -> None: """ Move...
import unittest from main import Board class TestBoard(unittest.TestCase): def test_init_board(self): board = Board(['X', 'O'], empty_square='a') board.squares = ['a']*9 board.current_player = 'X' board.players = ['X', 'O'] board.empty_square = 'a' def test_move(self)...
""" High Level Description: The recursive implementation fibonacci does a lot of repeated work, we can decrease the time complexity greatly by storing the Fibonacci numbers calculated so far. Time Complexity: O(n) """ def fibonacci(n): FibArray = [0, 1] while len(FibArray) < n + 1: ...
# https://stackabuse.com/random-forest-algorithm-with-python-and-scikit-learn/ import pandas as pd import numpy as np from sklearn.model_selection import train_test_split import graphviz import pydotplus from sklearn import metrics from IPython.display import Image from sklearn.tree import export_graphviz from skle...
import sqlite3 import json import oauth2 import urllib import urllib2 # Load randomized recent restaurant inspections. Restaurant names and addresses will be used to query yelp api. conn = sqlite3.connect('../data/food_inspections.db') c = conn.cursor() c.execute('SELECT * FROM inspections_clean_restaurants_recent_nor...
''' Encapsulation demonstration in Python ''' class Person(object): def __init__(self): self.Name = "Tudor" # public attribute self.__Surname = "Plugaru" # private atribute def PrintNameSurname(self): print self.Name + " " + self.__Surname p = Person() print p.Name # should be "Tu...
# written by oliver hamburger # program is an original game called "star runner" # last modified 1/19/17 import pygame class Man(pygame.sprite.Sprite): """class sets what is needed for spaceship/man """ def __init__(self, screen): super().__init__() self.image = pygame.image.load("ship.png")...
##################################################################################################### # The included python script provides a coding solution to analyze a Bank's Profit and Loss position # on a month over month basis. # Name: K. Ramsay # Created: 2/3/2020 # Updated: 5/4/2020 ###########################...
from sys import exit from random import randint from textwrap import dedent class Scene(object): def enter(self): print("This scene is not yet configured.") print("Subclass it and implement enter().") exit(1) class Engine(object): def __init__(self,scene_map): self.sc...
# -*- coding: utf-8 -*- """ Created on Mon Apr 5 15:14:21 2021 @author: Sohom Chatterjee """ #Machine Learning - Linear Regression #Car driving risk analysis using Linear Regression model #importing library import sklearn import numpy as np import pandas as pd import matplotlib.pyplot as plt #Read ...
x = int(input()) print('YES') if (x % 4 == 0 and x % 100 != 0) or x % 400 == 0 else print('NO')
x = set(int(x) for x in input().split()) y = set(int(x) for x in input().split()) print(*sorted(x.intersection(y))) #print(*sorted(set(input().split()).intersection(set(input().split()))))
def summ(): a = int(input()) if (a == 0): print(a) return a if summ() == 0: print(a) return 0 summ()
# -*- coding: utf-8 -*- """ Created on Fri Oct 28 20:33:49 2016 @author: RichardG """ def deep_reverse(L): for i in L: if type(i)==list:deep_reverse(i) L.reverse()
# -*- coding: utf-8 -*- """ Created on Sat Sep 17 16:31:39 2016 @author: RichardG """ def oddTuples(aTup): ''' aTup: a tuple returns: tuple, every other element of aTup. ''' # Your Code Here rTup = () index = 0 while index < len(aTup): rTup += (aTup[index],) ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 精度と再現率 """ import sys def main(): # 再現率と適合率を計算するための総数を保持する correct_sum = 0 # 正解の総数 true_bounds_sum = 0 # 正解の境界の総数 answers_bounds_sum = 0 # システム出力の境界の総数 # 標準入力から入力 for trues, answers in stdin2trues_answers(): # 正解とシステム出力の境界を取得 ...
# put your python code here A = input() B = input() H = input() def arithematic_func(first_number, second_number, operations): operations_list = ['+', '-', '/', '*', 'mod', 'pow', 'div'] first_number = float(first_number) second_number = float(second_number) if second_number == 0.0 and (operations in ...
import queue from collections import namedtuple Edge = namedtuple('Edge', ['vertex', 'weight']) class GraphUndirectedWeighted(object): def __init__(self, vertex_count): self.vertex_count = vertex_count # Contains the list of vertices in the graph self.adjacency_list = [[] for _ ...
import os #Permet de mettre en pause le programme from random import randrange #Génère un nombre aléatoire from math import ceil #Arrondir à l'entier supérieur def fonctionSaisie(type, min=0, max=100000): #Vérifier la saisie de l'utilisateur saisie = min while saisie <= min or saisie > ...
# primer programa import random myName = input('hola quin és el teu nom? ') print('encantat de coneixet, ' + myName, "Sabies que el teu nom té", len(myName), ' lletres ?') myAge = input('Quants anys tens? ') print('molt bé!! que gran que ets!!!, saps que en tindras ' + str(int(myAge) + 10) + ' en deu ...
from dados import products, students, my_list new_list = map(lambda x: x * 2, my_list) print() print(list(new_list)) new_list = [x * 2 for x in my_list] print() print(list(new_list)) for product in products: print(product) pricies = map(lambda p: p['price'], products) for price in pricies: print(price) d...
# Python program to calculate hashes of files # and output results to a .csv formatted file. import os import hashlib import csv # Pre-defined columns with values from coursework specification columns = ['Unique Reference Number', 'Filename', 'MD5', 'SHA-1'] # Create new file in 'write' mode f = open('File Hash Tabl...
# Chapter 7: Files # Exercise 2: Write a program to prompt for a file name, # and then read through the file and look for lines of the form: # 'X-DSPAM-Confidence: 0.8475'. # When you encounter a line that starts with "X-DSPAM-Confidence:', # pull apart the line to extract the floating-point number on the line. # Coun...
# Chapter 7: Files # Exercise 1: Write a program to read through a file and print the contents # of the file (line by line) all in upper case. fname = input('Enter a file: ') fhand = open(fname) for line in fhand : line = line.rstrip() line = line.upper() print(line)
#!/usr/bin/python3 def is_solved(solved, bags): for bag in bags: if bag['pattern'] not in solved: return False return True def solve_bag(bags, solved): num_bags = 0 for bag in bags: num_bags += (bag['amount'] * solved[bag['pattern']]) + bag['amount'] return num_bags ...
# 用最少数量的箭引爆气球 # 在二维空间中有许多球形的气球。对于每个气球, # 提供的输入是水平方向上,气球直径的开始和结束坐标。 # 由于它是水平的,所以纵坐标并不重要, # 因此只要知道开始和结束的横坐标就足够了。开始坐标总是小于结束坐标。 # 一支弓箭可以沿着 x 轴从不同点完全垂直地射出。在坐标 x 处射出一支箭, # 若有一个气球的直径的开始和结束坐标为 xstart,xend, 且满足 #  xstart ≤ x ≤ xend,则该气球会被引爆。可以射出的弓箭的数量没有限制。 # 弓箭一旦被射出之后,可以无限地前进。我们想找到使得所有气球全部被引爆, # 所需的弓箭的最小数量。 # 给你一个数组 points ,其中...
#!/usr/bin/env python3 """ --- Day 25: Let It Snow --- Merry Christmas! Santa is booting up his weather machine; looks like you might get a white Christmas after all. The weather machine beeps! On the console of the machine is a copy protection message asking you to enter a code from the instruction manual. Apparentl...
#!/usr/bin/env python """ --- Day 16: Dragon Checksum --- You're done scanning this part of the network, but you've left traces of your presence. You need to overwrite some disks with random-looking data to cover your tracks and update the local security system with a new checksum for those disks. For the data to not...
#!/usr/bin/env python3 # -*- coding: <encoding name> -*- """ --- Day 8: Matchsticks --- Space on the sleigh is limited this year, and so Santa will be bringing his list as a digital copy. He needs to know how much space it will take up when stored. It is common in many programming languages to provide a way to escape...
#!/usr/bin/env python """ --- Day 10: Balance Bots --- You come upon a factory in which many robots are zooming around handing small microchips to each other. Upon closer examination, you notice that each bot only proceeds when it has two microchips, and once it does, it gives each one to a different bot or puts it i...
#!/usr/bin/env python """ --- Day 14: One-Time Pad --- In order to communicate securely with Santa while you're on this mission, you've been using a one-time pad that you generate using a pre-agreed algorithm. Unfortunately, you've run out of keys in your one-time pad, and so you need to generate some more. To genera...
#!/usr/bin/env python3 # -*- coding: <encoding name> -*- """ --- Day 9: All in a Single Night --- Every year, Santa manages to deliver all of his presents in a single night. This year, however, he has some new locations to visit; his elves have provided him the distances between every pair of locations. He can start ...
#!/usr/bin/env python """ --- Day 23: Safe Cracking --- This is one of the top floors of the nicest tower in EBHQ. The Easter Bunny's private office is here, complete with a safe hidden behind a painting, and who wouldn't hide a star in a safe behind a painting? The safe has a digital screen and keypad for code entry...
#!/usr/bin/env python """ --- Day 9: Stream Processing --- A large stream blocks your path. According to the locals, it's not safe to cross the stream at the moment because it's full of garbage. You look down at the stream; rather than water, you discover that it's a stream of characters. You sit for a while and reco...
#!/usr/bin/env python """ --- Day 11: Hex Ed --- Crossing the bridge, you've barely reached the other side of the stream when a program comes up to you, clearly in distress. "It's my child process," she says, "he's gotten lost in an infinite grid!" Fortunately for her, you have plenty of experience with infinite grid...
#!/usr/bin/env python """ --- Day 15: Timing is Everything --- The halls open into an interior plaza containing a large kinetic sculpture. The sculpture is in a sealed enclosure and seems to involve a set of identical spherical capsules that are carried to the top and allowed to bounce through the maze of spinning pie...
#!/usr/bin/env python """ --- Day 4: High-Entropy Passphrases --- A new system policy has been put in place that requires all accounts to use a passphrase instead of simply a password. A passphrase consists of a series of words (lowercase letters) separated by spaces. To ensure security, a valid passphrase must conta...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jan 16 21:59:52 2019 @author: aditiadeshshenoy """ #Code Challenge 1: Implemented PatternCount (1.2.1) fo = open("dataset_2_10.txt", "r") line = fo.readlines() seq = (line[0]) k = (line[1]) k = k.rstrip() def PatternCount(Text,Pat): n = (len(seq)-...
s = [88, 92, 74, 48, 73] #student scores print(sum(s)/len(s)) #calculating mean of the scores s1 = [x ** 0.5 * 10 for x in s] #curves scores with sq root method and store in new list print(sum(s1)/len(s1)) #print mean of curved scores # without the comments it is hard to understand what is going on here
def Sorting(lst): lst2 = sorted(lst, key=len, reverse=True) print (lst2) states = ["Abia", "Adamawa", "Anambra", "Akwa Ibom", "Bauchi", "Bayelsa", "Benue", "Borno", "Cross River", "Delta", "Ebonyi", "Enugu", "Edo", "Ekiti", "Gombe", "Imo", "Jigawa", "Kaduna", "Kano", "Katsina", "Kebbi", "Kogi", "Kwara", "Lago...
#!/usr/bin/python3 import socket import argparse #url="challenges.ctfd.io" #chalport=30129 def create_conn_object(func_url, func_port): conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) conn.connect((func_url, int(func_port))) conn.recv(1024) return conn def brute_force(conn_object, reject, p...
print "\nhere is another way to collect info with raw_input\n" first = raw_input("first name >") last = raw_input("last name >") eyes = raw_input("eye color >") weight = raw_input("weight >") add = raw_input("size >") print "\n\nhello " + first + last + ", I like your" + eyes +"eyes. I bet you weight about" + weight +...
a = int(input("Bir sayı giriniz")) #str b = int(input("Bir sayı giriniz")) c = int(input("Bir sayı giriniz")) max = a min = b if b > max: max = b if c > max: max = c if a < min: min = a if c < min: min = c print("En büyük sayı {} \nEn küçük sayı {}".format(max, min))
#Fonksiyon tanımlamaları def menu(): print("******Hesap Makinesi******") print("İşlemler") print("1-Toplama\n2-Çıkarma\n3-Çarpma\n4-Bölme\n5-Üs Alma") islem = int(input("Yapılacak İşlemi Seçiniz : ")) return islem def toplam(sayi1, sayi2): return sayi1+sayi2 def cikarma(x, y): return x-...
""" range(stop) 0 dan stop değerine kadar range(start, stop) start değerinden stop değerine kadar range(start, stop, step) start değerinden stop değerine kadar step aralıklar ile """ # for(i = 0; i < 5;i++) # for i in 0 1 2 3 4 5 6 7 8 9 for i in range(10): print(i**2)
# #3x+1 problem # import timeit # import _thread # start = timeit.default_timer() # start_number = 295147905179352825856 # #x = int(input("Enter your number: ")) # count = 0 # x = int(848484848844/10000) # ser_val = start_number+848484848844/10000 # def problemLoop(start_number,x): # for i in range(start_nu...
class Queue: def __init__(self): self.data = [] def enqueue(self, elt): self.data.append(elt) def dequeue(self): return self.data.pop(0) def peek(self): return self.data[0] def queue_test(data, reference_arr): index = 0 while index < len(data): if da...
def is_symmetric(s): return s == s[::-1] def is_symmetric_unit_test(s, value): print("testing is_symmetric on input '", s, "'", sep='') assert is_symmetric(s) == value print("PASSED") print() is_symmetric_unit_test('racecar', True) print() is_symmetric_unit_test('batman', False)
def convert_to_numbers(s): letter_dict = { ' ': 0, 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, ...
temperature = input("Enter your temperature:") temperature = int(temperature) if(temperature>=100): print("Water is in gaseous state") elif(temperature>0): print("Water is in liquid state") elif(temperature<=0): print("Water is in solid state")
num1 = input("Enter your number") num2 = input("Enter your number") num3 = input("Enter your number") def smallest(x, y, z): return min(x, y, z) a = smallest(num1, num2, num3) print(a)
num1 = int(input("Enter your number")) num2 = int(input("Enter your number")) num3 = int(input("Enter your number")) def average(num1 , num2 , num3): return (num1 + num2 + num3) / 3 a = average(num1, num2, num3) print(a)
# lists in python # declaring a list list = [1,2,"Aized",3.01,'a','@#^'] # adding elements to a list # concatenation list = list + ["aized"] # using the append method list.append("sumbal") # using the extend method list.extend("sumbal") list_2 = ["ammar", "saqib"] # list.append(list_2) list.extend(list_2) # ch...
num1 = input("Enter first number:") num2 = input("Enter second number:") num3 = input("Enter third number:") if (num1<num2 and num1<num3 and num2<num3) or (num1>num2 and num1>num3 and num2>num3) : print("The numbers are in order") else: print("The numbers are not in order")
# -*- coding: utf-8 -*- """ Created on Wed Aug 22 10:45:16 2018 @author: allokik pranshu """ def key_matrix(b): if b==2: key=[[0 for x in range(2)] for y in range(2)] for i in range(2): key[i][0],key[i][1]=map(int,input("Enter the values of row ").split(" ")) else: ...
a1 = int(input()) a2 = int(input()) b1 = int(input()) b2 = int(input()) c1 = int(input()) c2 = int(input()) a = ((a1-b1)**2 + (a2-b2)**2) b = ((b1-c1)**2 + (b2-c2)**2) c = ((c1-a1)**2 + (c2-a2)**2) if a + b == c or a + c == b or b + c == a: print('yes') else: print('no')
# # value of the variable becomes the key in the dictionary # someKey = 3 # d = { # someKey: 'three' # } # # print(d[3]) # # setting default if value in dict. is not found # print(d.get(5, 'five')) # #### Dictionaries # student = { # 'name': 'Maria', # 'course': 'SEI', # 'current_week': 7 # } # 1 # ski...
# first_module.py def addition(): print("Add") print("x = {}".format(x)) c = a + b print("{} + {} = {}".format(a, b, c)) return if __name__ == "__main__": x = input("Input a command: ") print("You entered {}.".format(x)) a = 1 b = 2 if x == 'add' or x == 'a': addi...
''' Created on 12-Jun-2017 @author: mohan.chinnaiah ''' #create a tuple tuplex = 4, 8, 3 print(tuplex) n1, n2, n3 = tuplex #unpack a tuple in variables print(n1 + n2 + n3)
x={ 'test1':1, 'test2':2, 'test3':3 } my_keys = ('test1','test2') y=dict(filter(lambda t: t[0] in my_keys, x.items())) print(y)
class Triangle: def __init__(self,base,height): self.base=base self.height=height def area(self): return (.5 * self.base * self.height) def __add__(self, anothertriangle): return Triangle(self.base+anothertriangle.base,self.height+anothertriangle.height) t1=Triangl...
# my_dict = {'key1': 'value1', 'key2': 'value2'} # print(my_dict) # print(my_dict['key1']) d = {'k1': 123, 'k2': [0, 1, 2], 'k3': {'insideKey': 100}} print(d['k2'][2]) print(d['k3']['insideKey']) d = {'key1': ['a', 'b', 'c']} my_list = d['key1'] # print(my_list) letter = my_list[2] # print(letter) letter.upper() print(...
from collections import namedtuple # t = (1, 2, 3) Dog = namedtuple('Dog', 'age breed name') sam = Dog(age=2, breed='Lab', name='Sammy') print(sam.age) print(sam.name) # is just like a tuple but basically create a new object type and allows names for various field Cat = namedtuple('Cat', 'fur claws name') c = Cat(fur...
# def name_function(): # """ # DOCSTRING: Information about the function # INPUT: # OUTPUT: # :return: NO # """ # print("Hello") # # # def say_hello(name='NAME'): # return 'hello ' + name # # # result = say_hello('Simona') # # print(result) # # def add(n1, n2): # return n1 + n2 # # #...
def zgadywanka(): print("Pomyśl liczbę 1-1000 a ja zgadną ją w max. 10 prób") zgadywanka.z_min = 1 zgadywanka.z_max = 1000 def za_duzo(): zgadywanka.z_max = zgadywanka.guess def za_malo(): zgadywanka.z_min = zgadywanka.guess def zgadlem(): print("Wygrałem!") def ...
finaliza = True limitePessoas = 2 aNome = [] aSalario = [] def testeMenu(arg): if arg == 0: print("Finalizar.") finalizaPrograma() global finaliza finaliza = False elif arg == 1: print("Cadastrar.") cadastra() elif arg == 2:...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 04/02/2018 5:02 PM # @Author : Lee # @File : min_heap.py # @Software: PyCharm import random class MinHeap(object): """ 原理与MaxHeap一致 故不多做注释 """ def __init__(self, arg): if isinstance(arg, int): self.capacity = arg ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 05/02/2018 11:49 PM # @Author : Lee # @File : heap_sort.py # @Software: PyCharm from utils.sort_test_helper import SortTestHelper class HeapSort(object): """ 这种堆排序不在调用最大堆的数据结构 直接在原数组上进行shift_down操作完成堆排序 BTW:最大堆在实现上,数组从1开始索引,此处数组则从0开始索引 ...
# Author: Jaime Justo # Date: 3/2/21 import random class PuzzleBoard: def __init__(self, tiles_given=None): self.rows = 3 self.cols = 3 self.empty_space_row = None self.empty_space_col = None self.board = self.new_board(tiles_given) def new_board(self, tile_order=None...
import re import csv import sys input_file= sys.argv[1] output_file=sys.argv[2] pattern=re.compile(r'(?P<my_pattern_group>^001-.*)', re.I) with open(input_file,'r',newline='')as csv_in_file: with open(output_file,'w',newline='') as csv_out_file: filereader=csv.reader(csv_in_file) filewriter=csv.w...
# coding: cp949 print(" α׷ ver2.0") star = int(input("Ȧ Էϼ(0 <- ): ")) while True: if star%2 !=0: for i in range(1, int(star/2)+1): print(" "*(int(star/2)-i+1) + "*"*(2*i-1)) for j in range(int(star/2)+1,0,-1): print(" "*(int(star/2)-j+1) + "*"*(2*j-1)) break e...
# Zadanie nr 1 # Pytaj użytkownika o liczbę tak długo aż poda liczbę parzystą lub przekroczy limit 10 prób. even_number = int(input("Podaj liczbę parzystą: ")) attempt = 1 is_even = "" print("") while even_number % 2 != 0 and attempt < 10: print(f"Niestety, {even_number} to nie liczba parzysta, spróbuj p...
# Zadanie nr 2 # Poproś użytkownika o wprowadzenie listy zakupów, rozdzielając poszczególne elementy przecinkiem. # Następnie powiedz (wypisz), czy jest to według Ciebie długa lista, czy też nie. shopping = input("Wprowadź listę zakupów, rozdzielając poszczególne elementy przecinkiem: ") shopping_list = shopping....
def mean(*a): return sum(a) / len(a) print(f"{mean(4,5,3 ,5,6,7,8,9)=}") print(f"{mean(1,4,6,82,5,7,7,2,5,6,8)=}") print(f"{__name__=}")
import numpy as np import matplotlib.pyplot as plt from scipy.spatial import distance_matrix as distance from agent import agent class Grid: """ Make a plain grid for the bots to play in input: n: size of square grid(int) agents: the set of agents """ def __init__(self,n = 10,Map =...
t=int(input("Enter the no. of terms: ")) a,b=0,1 print(a,end='') print(b,end='') for t in range(0,t-2): c=a+b print(c,end='') a=b b=c
# coding:utf-8 """ Given a string, find the length of the longest substring without repeating characters. 找出不重复的最长子字符串 Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. 题目地址: https://leetcode.com/problems/longest-substring-without-repeating-...
# coding:utf-8 """ Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. Example 1: Input: "(()" Output: 2 Explanation: The longest valid parentheses substring is "()" 题目地址:https://leetcode.com/problems/longest-...
# coding:utf-8 """ Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water ( blue section) are be...
__author__ = 'yz48' # bubble sort def bubble_sort(array): for i in range(len(array)): f = 0 for j in range(1,len(array)-i): if array[j-1] > array[j]: f = 1 array[j-1], array[j] = array[j], array[j-1] if f == 0: break return array ...
def ets(): m=[] n=int(input("Enter n: ")) for i in range(0,n): x=input("Enter the seat number: ") m.insert(i,x) print(m)
#4th exercise for the first semester class introduction to programming in UniPi #Python is 3.7 def calculation(x): L=[] number = '' # puts every character's ascii hex in a list for i in x: L.append(ord(i)) print("Every character of", x,"'s ascii value in a list") print(L) # creates...
# If we list all the natural numbers below 10 that are # multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of # these multiples is 23. Find the sum of all the multiples # of 3 or 5 below 1000. val = (3 + 999) * (999 / 3) / 2 + (5 + 995) * (995 / 5) / 2 - (15 + 990) * (990 / 15) / 2 print(val)
# -*- coding: utf-8 -*- """ Created on Tue Oct 20 17:09:50 2020 @author: Saraswati """ n=int(input()) # input how many socks list1=[] # for storing socks color # input each socks color for i in range(n): r=int(input()) list1.append(r); dict1={} # for storing each unique color socks # co...
def ten(tn): if(tn=="10"): return "Ten" elif(tn=="11"): return "Eleven" elif(tn=="12"): return "Twelve" elif(int(tn[1])>2): return num(tn[1])+"teen" def num(d): if(d=="2"): return "Twen" elif(d=="3"): return "Thir" elif(d=...
#/usr/bin/python import sys S = [[1,2],[2,4]] L = [] # Adds the elements of a set into L def addL(set,L): for each in set: L.append(each) return L # L will contain a list of elements contained in the set L = addL(S[0],[]) # Start the index at 1 since weve already added the first S index = 1 while index < le...
import math def main(): x, y, x1, y1, x2, y2 = map(int, input().split()) if x1 <= x and x2 >= x: print(min(abs(y1-y), abs(y2-y))) elif y1 <= y and y2 >= y: print(min(abs(x1-x), abs(x2-x))) else: print(min(math.hypot(x1-x, y1-y), math.hypot(x2-x, y-y2), math.hypot(x1-x, y2-y), math.hypot(x2-x, y1-y)...
def main(): cases = int(input()) for _ in range(cases): words = input().split(' ') x = set() y = input().split(' ')[2] while y != 'the': x.add(y) y = input().split(' ')[2] else: out = [] for word in words: if word not in x: out.append(word) print('...
def main(): d, m = map(int, input().split()) day = 2+d m -= 1 while m > 0: if m in [1,3,5,7,8,10,12]: day += 31 elif m in [4,6,9,11]: day += 30 else: day += 28 m -=1 out = "" day %= 7 if day == 0: print("Monday") ...
words = {} def main(): global words day = 0 while True: try: line = input() if line[:5] = '<top ': printtop(int(line[5]), day) line = input() continue if line == '<text>': while line != '</text>': ...
print('------Hoja de trabajo 2-------') print('#########Ejercicio 1##########') triangulo=int(input("Ingrese un número entero:")) o="" for i in range (0, triangulo, 1): o=o+"*" print(o) print('##########Ejercicio 2#########') numero=int(input("Ingrese un número entero:")) if numero>=0: if numero % 2 ...
def parse_path(text): ''' Parsing path to return the path and filename ''' text = text.replace('\\', '/') names = text.split('/') print(names) trail = names[len(names)-1].split('.') if len(trail) > 0: namefile = trail[0] else: namefile = names[len(names)-1] ...
alpha = 'абвгдеёжзиклмнопрстуфхцчшщъыьэюя' alphaUp = alpha.upper() number = int(input('Input a number: ')) summ = '' def changeChar(char): if char in alpha: return alpha[(alpha.index(char) + number) % len(alpha)] elif char in alphaUp: return alphaUp[(alphaUp.index(char) + number) % len(alphaUp...
# 16.9.1 class Triangle: def __init__(self, a, b, c, x, y): self.a = a self.b = b self.c = c self.x = x self.y = y def __str__(self): return f'{self.__class__.__name__} \nДлина стороны а: {self.a}, \nДлина стороны b: {self.b}, \nДлина стороны c:' \ ...
''' COIN TOSS PROGRAM ----------------- 1.) Create a program that will print a random 0 or 1. 2.) Instead of 0 or 1, print heads or tails. Do this using if statements. Don't select from a list. 3.) Add a loop so that the program does this 50 times. 4.) Create a running total for the number of heads and the number of ta...
""" Apply Abstract-Class that includes Data-Structure System. """ import collections.abc as abc # Check Abstract-Methods that implemented # in the Sequence-Class. abc.Sequence.__abstractmethods__ # Check Abstract-Methods of MMutable-Sequence-Class. abc.MutableSequence.__abstractmethods__ # Check the Relationship...