text
stringlengths
37
1.41M
# Do not modify this file # read file into a table (list of list of strings) def get_table_from_file(file_name): with open(file_name, "r") as file: lines = file.readlines() table = [element.replace("\n", "").split(";") for element in lines] return table # write a table (list of list of strings) ...
# Noah van der Vleuten (s1018323) # Jozef Coldenhoff (s1017656) import exceptions import shop # contains FruitShop class definition def shop_smart(order: list, shops: list) -> shop.FruitShop: """ Calculate at which shop the given order is cheapest. :param order: (list) a list of (fruit, amount) tuples ...
#!/usr/bin/env Python # coding=utf-8 """ 统计考试成绩 """ from __future__ import division def average_score(scores): """ 统计平均分. """ score_values = scores.values() sum_scores = sum(score_values) average = sum_scores/len(score_values) return average def sorted_score(scores): "...
MINING_REWARD = 10 #placed this in all caps because it is a global variable #Initializing our (empty) blockchain list genesis_block = { 'genesis_hash': '', 'index': 0, 'transactions': [] } #1) Initialising blockchain list (array) blockchain = [genesis_block] open_transactions = [] owner = 'ZK' #unique ide...
import os, sys import pygame from pygame.locals import * #Yell at the user for having buggy pygame. if not pygame.font: print('[WARN]:Fonts disabled.') if not pygame.mixer: print('[WARN]:Sound disabled. There will be no music.') #Game main class. #This class handles main init and game creation. class PyManMain: ...
from nltk.corpus import words word_list = words.words() print "Enter your characters here. If there is any guess word use '?' for that." input_letters = raw_input() #convert text to list of individual characters input_letters_list = list(input_letters) #number of ? (guess words) present in input guess_words = input_le...
def find_needle(haystack): for words in haystack: if words == "needle": return "found the needle at position" + " " + str(haystack.index("needle"))
''' Your function should take in a single parameter (a string `word`) Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters. Your function must utilize recursion. It cannot contain any loops. ''' # def count_th(word): # # takes in word # # case matters # ...
def getListPrice(): return getNumbers("\n\n-------------------------------------\n\nPlease enter the list price: ") def getNumberOfPromos(): return getNumbers("\n\nPlease enter the number of promotions: ") def getNumbers(message): tryAgain = True while(tryAgain): number = input(message) ...
radius = int(input("Enter the radius :")) area = 3.14 * radius ** 2 print("Area of the circle is",area,"sqaure units")
def crypt_caesar(input): string = input.split(' ')[1].lower() move = ord(input.split(' ')[0].lower()[0])-97 return ''.join([chr(ord(i)+move if ord(i)+move < 123 else ord(i)+move-26) for i in string]) # print(crypt_caesar('snitch thepackagehasbeendelivered'))
# get the id's of users who have retweeted the status id #retweeteduser = {} searchWord = input("Please enter a search term: ") filepath = searchWord.replace(" ","").lower() with open(filepath+'.json', 'r') as fr: data = json.load(fr) influential_tweets = {} for key in data: #print('key: ',key) #print('r...
# Assignment 5 # Name: Winston Lu # Block: 1-4 # # Task A: Create a function called binary(n) that returns the binary string of n, # where n is a non-negative integer. Do not use bin(n) function. Include exceptions. def binary(n): if (type(n) == int or type(n) == float): if (n==0): return(0) ...
#Name: Hangman game #Description: Allows users #Author: Alia #Date: 28/1/2018 #Version:1 #title of the game print ("Hangman Game") #importing the time module import time #welcoming the user name = input("what is your name? ") print ("Hello, " + name," Lets play hangman!") #wait for 1 second time...
from typing import Dict, Hashable, Iterable, Tuple, Union Vertex = Hashable Edge = Union[Tuple[Vertex, Vertex, float], Tuple[Vertex, Vertex]] def source_target_dijkstra_cost(vertices: Iterable[Vertex], edges: Iterable[Edge], source: Vertex, ...
NAMES = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] NAMES_LENGTH = [len(name) for name in NAMES] NAMES_TENS = ['', 'ten', 'twenty', 'thirty', 'forty', 'fifty'...
def armstrong(x): x=str(x) sum=0 for i in range(len(x)): sum+=(int(x[i]))**3 if int(x)==sum: print(x) else: return lower=int(input("Enter lowest range:")) higher=int(input("Enter higher range:")) print("Armstrong number btween",lower,"and",higher,"are") for x in range(lower,higher+1): armstrong(x)
start = int(input('Start at: ')) list_val=[] dis=[] Num_points=int(input('Number of points: ')) for i in range(1,Num_points+1): val=int(input('Value'+str(i)+': ')) list_val.append(val) print(list_val) for k in range(0,len(list_val)): while len(list_val)!=0: distance=int(input('Distance from',list_val[k],' to ',lis...
# Book problem (Pearson). x = int(input('Enter Number:')) b = [] end = 7 for i in range(1,end): b.append(i*x) print(b)
def areaTriangle(sidea, sideb, sidec): x = (sidea+sideb+sidec)/2 a = (x*(x-sidea)*(x-sideb)*(x-sidec))**1/2 return a def main(): side1 = float(input('Side 1: ')) side2 = float(input('Side 2: ')) side3 = float(input('Side 3: ')) areaTri = areaTriangle(side1, side2, side3) print(areaTri, '...
def speed_limit(speed): if speed <=90: message = 'No Punishment and No Warning' if speed>=91 and speed<=110: warn = (speed-90)*300 message = warn,'Warning' if speed>110: warn = (speed-90)*500 message = warn,'License Removed' return message def main(): speed = ...
print('Enter Matrix A') row_1A = [] row_2A = [] row_3A = [] for i in range(1,4): R1 = int(input('Enter Element of Row '+str(i)+ ' Column 1 = ')) row_1A.append(R1) for i in range(1,4): R2 = int(input('Enter Element of Row '+str(i)+ ' Column 2 = ')) row_2A.append(R2) for i in range(1,4): R3 = int(input('Enter Elemen...
#server side code import socket import sha1code #create a server side socket object serversocket =socket.socket(socket.AF_INET,socket.SOCK_STREAM) #create a unix domain stream socket #get the hostname of local machine hostname= 'localhost' print hostname port = 12345 #port to which server will be listening #bind the...
def sumar(x,y): return x+y print sumar(3,2) def f(x,y): return x*2,y*2 print f(1,2) a,b=f(1,2) print(a) print(b)
#usr/bin/env python #-*- coding utf-8 -*- #Filename argv.py from sys import argv script, first, second, third = argv print ("The script is called:", script) print ("Your first variable is:", first) print ("Your second variable is:", second) print ("Your third variable is:", third)
import numpy as np import math """ Contains the definition of the agent that will run in an environment. """ class epsilon_greedy: def __init__(self): """Init a new agent. """ self.counts = [0] * 10 self.values = [0] * 10 self.epsilon = 0.1 def act(self, observation...
#!/usr/bin/env python import json def get_data_from_json(file): with open(file, 'r') as json_file: return json.load(json_file) def find_key_pairs(obj, keys, found_pairs=[]): """Traverses a nested dictionary and lists to find a key, or list of key pairs and returns all parent dictionaries tha...
""" Apply backtrack + forward checking to find all solutions of n-queens problem Remarks: 1. for 8 queens, there are 92 unique solutions """ from util import * def solve(nqns): row_i = 0 qns = []; qns_sets = [] tmp = backtrack_all(nqns, row_i , qns, qns_sets) if len(qns_sets) == 0: print('No solution is found'...
import turtle ob = turtle.Turtle() ob.getscreen().bgcolor("red") ob.up() ob.goto(0, -100) ob.down() ob.begin_fill() ob.fillcolor("yellow") ob.circle(100) ob.end_fill() ob.up() ob.goto(-67, -40) ob.setheading(-60) ob.width(5) ob.down() ob.circle(80, 120) ob.fillcolor("black") for i in range(-35, 1...
#!/usr/bin/env python # -*- coding: utf-8 import re m = re.findall('abc', 'aaaaabcccabcc') print(m) m = re.findall('\d', 'abc1ab2c') print(m) m = re.findall('\d\d\d\d', '123abc1234abc') print(m) m = re.findall(r'<div>(.*)</div>', '<div>hello</div>') print(m) m = re.findall(r'<div>(.*)</div>', '<div>hello</div><di...
import random from card import Card class Deck: suites = ['hearts', 'spade', 'diamond', 'clubs'] value = list(range(2, 10)) value.extend(['jack', 'queen', 'king', 'ace']) cards = [] def __init__(self): for s in self.suites: for v in self.value: self.cards.appen...
from tkinter import * import random class Map: def __init__(self, master): self.master = master rules = Label(self.master, text = 'find the bomb by pressing on the buttons with hint of direction', wraplength = 400, font = ('Courie', 14)).grid(columnspan = 3, row = 0) label1 = Label(self.mas...
import urllib2 # download file from web def downHTTP(server, url, local_filename=None): # extract filename from url filename = url.split('/')[-1].split('#')[0].split('?')[0] if not local_filename: local_filename = filename # open file server.send('Downloading: ' + filename + ' > ' ...
def PrintMenu(): print("1.Citeste lista") print("2.Elimina numere prime din lista") print("3.Afisati daca media aritmetica a numerelor este mai mare decat n") print("4.Adauga la lista numarul de divizori proprii ai elementului") print("5.Compune tuplu cu numarul,indexul lui si numarul de aparitii") ...
from typing import List import matplotlib.pyplot as plt import requests from pandas import DataFrame def fetch_symbols() -> List[str]: url = "https://api.exchangeratesapi.io/latest" response = requests.get(url) response_json = response.json() return sorted(response_json["rates"].keys()) def fetch( ...
def count_range(list, min, max): counter = 0 for x in list: if min <= x <= max: counter += 1 return counter numlist = [1,2,3,4,5,6,7,8,9,10] print(count_range(numlist, 3, 9))
file1 = open('email.txt', 'r') lines = file1.read() emailAdds = [] endings = ['com', 'edu', 'gov', 'org'] for string in lines.split(): if '@' in string: emailAdds.append(string) for email in emailAdds: email = email.replace(";","") if email[-3:] in endings: print(email + " : valid") else: pri...
def factorial(num): def intCheck(num): return True if isinstance(num, int) is True else False return num * factorial(num-1) if intCheck(num) and num > 0 else 1 print(factorial(5))
import collections Point = collections.namedtuple('Point',['name', 'x', 'y']) class ExistingPointError(Exception): def __init__(self): self.message = "ExistingPointError Exception Thrown" def __str__(self): return self.message class PointNotFoundError(Exception): def __init__(self): ...
L = [] for x in range(1,6): L.append((x*10, x*10, x*10)) print(L) print("After removing : ") L.pop() print(L) print("inserting before last: ") h = 111, 64, 45 L.insert(len(L) - 1, h) print(L) print('{0:>10}{1:>10}{2:>10}'.format('X', 'Y', 'Z')) for x, y, z in L: print('{0:>10}{1:>10}{2:>10}'.format(x, y, z)...
import math from Geometry import Point __author__ = 'Tan' def get_vector_length(vector): return math.sqrt(vector.x * vector.x + vector.y * vector.y) def get_angle_between_two_vectors(a, b): len_a = get_vector_length(a) len_b = get_vector_length(b) if len_a * len_b == 0: return 0 c = ...
''' Day 4 - Advent of Code ''' import re def readInput(file): ''' Parses the input file for passport entries, returning an array of passport entries in key:value pair format ''' with open(file) as f: # Passport entries are separated by a blank line (in other words, # two newlines) ...
# Python program to demonstrate the # use of join function to join list # elements without any separator. # Joining with empty separator list1 = ['g','e','e','k', 's'] print("".join(list1)) geeks class Solution: def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool: dictm = {'...
# One number per line, return a list with int def number_per_line(filepath): return list_to_int(entry_per_line(filepath)) # Each line represents a list, split by a specific sequence def list_per_line(filepath, delimiter): return split_strings_in_list(entry_per_line(filepath), delimiter) def split_strings_in_...
from math import atan2, pi class Point(): def __init__(self, x, y): self.x = x self.y = y def distance_to(self, point): a = abs(self.x - point.x) b = abs(self.y - point.y) return ( (a ** 2) + (b ** 2) ) ** 0.5 def angle_to(self, point): delta_x = point.x - ...
from math import atan2, pi class Point(): def __init__(self, x, y): self.x = x self.y = y def distance_to(self, point): distanceX = point.x - self.x distanceY = point.y - self.y return (distanceX ** 2 + distanceY ** 2) ** .5 def angle_to(self, point): delta...
# -*- coding: utf-8 -*- """ Created on Mon Nov 16 21:14:29 2020 @author: Pranav """ import pandas as pd import numpy as np import matplotlib.pyplot as plt from numpy import random #import math #import statistics as stats def sigmoid(x): # Sigmoid activation function: f(x) = 1 / (1 + e^(-...
"""Test the behavir of object with registered names.""" from data.base import db from test.base import BaseTest class TestNames(BaseTest): def test_split(self): """Split a name.""" character = self.create_character() names = character.names.split("this is a green mouse") # Just m...
#!/usr/bin/env python3 """ TreeHash is a Function enabling the user to compare nested dicts and lists by generating a hash. """ import hashlib import json def treehash(var): """ Returns the hash of any dict or list, by using a string conversion via the json library. """ return hashlib.sha256(json...
# python3 def gcd(a, b): """ Recursive algorithm of finding the greatest common divisor. :param a: integer number :param b: integer number :return: integer number """ # the algorithm is finished, when reminder from division (a % b) is equal to 0 if b == 0: return a return g...
#python3 import sys import math def optimal_summands(n): """ Implementation of maximum number of prizes. You have n rewards and need to find out which maximum number of prize places can you make. The restriction is that every higher place must has more rewards that the lower one. The goal of this pro...
#python3 import random import sys def merge_parts(a, left, middle, right): """ Algorithm of merging two sorted parts into one sorted part. Also while merging algorithm checks if pair for inversion and returns number of inversions. :param a: initial array :param left: left bound of first array that...
numbers = [1, 2, 3, 12, 17, 15] print("Here are the numbers available: ") for i in range(20): if i in numbers: continue print(i) x = 0 while x < 5: x += 1
# How to use range # range (start, end, step) # range is inclusive, exclusive # Loop from 0 to 9 startNum1 = 0 endNum1 = 10 for x in range(startNum1, endNum1): print (x) # Loop from 0 to 20 by 5's startNum2 = 0 endNum2 = 21 for x in range(startNum2, endNum2, 5): print (x) # Loop from 10 to 1 startNum3 = 10 e...
userString = input("Enter a string please:\n") if userString == userString[::-1]: print("Your word is a palindrome")
import time currentDate = (int)(time.strftime("%Y")) age = (int)(input("Please input your current age: ")) print("You will be 100 in the year {0}".format((currentDate - age + 100)))
import sqlite3 import json # SELECT DE TODOS OS REGISTROS NO BANCO DE DADOS DA TABELA 'Clinica' def select_all(): connection = sqlite3.connect('db_puppy.db') cursor = connection.cursor() cursor.execute("SELECT * FROM Clinica;") resultado = cursor.fetchall() cursor.close() connectio...
# Creating class in python class student: # Calss Variable perc_rise = 1.05 '''Using __init__() Initailze Method or Constructor method''' def __init__(self,firstname,lastname,marks): '''self is a instance''' self.firstname = firstname self.lastname = lastname self.m...
import pandas as pd import numpy as np df=pd.read_csv("LBW_Dataset.csv") inte=df.interpolate() #age is a numerical column. so the nan values are replaced by the median of the present values age=df['Age'].median() #print(age) age=round(age) df['Age']=df['Age'].fillna(age) #weight is a numerical column...
def gcd(a,b): """Compute the greatest common divisor of a and b""" while b > 0: a, b = b, a % b return a def lcm(n1,n2): masavi = 1 flg = 0 while True: i = 2 while i < n1 or i < n2: if(n1 % i == 0 and n2 % i == 0): n1 = n1//i ...
class Graph(object): """ This is a class for undirected graph """ def __init__(self, size, is_partition=False): """ :param size: number of nodes in the graph :param is_partition: whether this is a partition graph """ self._nodes = [set() for _ in ra...
import random a = input('Maxium: ') b = input('Minmum: ') a = int(a) b = int(b) rn = random.randint(a, b) c = 0 while True: n = input('Please guess the number: ') n = int(n) c = c + 1 if n == rn: print('Right.') print('You have already guessd', c ,'times') break elif n > rn: ...
import string def form_dict_letter_number(filename): dic = {} with open(filename, 'r') as f: for line in f: for letter in line.lower(): if letter.isalpha(): if letter in dic: dic[letter] += 1 else: ...
def even(): a = [x * 10 if x % 2 == 0 else x for x in range(0, 20)] print(a) even() def age(): a = int(input("how old are you")) if a < 18: print ("you are not old") else: print("you are old") age() print("\n\n\t\tthe year they were born") print("\n") def tell_age()...
def main(): #Empty dictionary to collect users responses={} #set flag condition to end or continue loop polling=True #while loop to fill responses while polling: name=input("Enter name: ") address1=input("House number and street: ") city=input("City: ") stat...
#class, enum, class variable/method, subClass, property, getter/setter, magic function/repr/deleter/add class Gender: Male =1 Female =2 class Human(object): Defense = 0 def __init__(self, first, last, age, gender, power): print "Human Created!" self.First = first self.Last = ...
from enum import Enum class Gender(Enum): Male = 1 Female =2 class BodyType(Enum): Fit = 1 Slim = 2 Heavy = 3 class Human(object): Age = 0 Gender = Gender.Male BodyShape = BodyType.Fit Eyes = 2 def __init__(self, age, gender, bodyShape ): print("hello world, one hum...
#!/usr/bin/env python # -*- coding: utf-8 -*- import re def validate_first_name(first): return len(first) >= 2 def validate_last_name(last): return len(last) >= 2 employee_id_re = re.compile("^[a-zA-Z]{2}-\d{4}$") def validate_employee_id(employee_id): return employee_id_re.match(employee_id) def valid...
#!/usr/bin/env python # -*- coding: utf-8 -*- from prompt import int_input from random import randint def score_msg(count): if count <= 1: msg = "You're a mind reader!" elif count <= 4: msg = "Most impressive." elif count <= 6: msg = "You can do better than that" else: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from prompt import int_input weight = int_input("Your weight in pounds: ") gender = input("Your gender (m/f): ").strip().lower() hours = int_input("Hours after drink: ") amount = int_input("Amount of drink in ounces: ") absorbtion_ratio = 0.73 if gender == 'm' else 0.6 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from word_tool import slice_text def count_words(text): words = [x[1] for x in slice_text(text) if x[0]] counts = {} for w in words: wl = w.lower() if wl in counts: counts[wl] += 1 else: counts[wl] = 1 ...
#!/usr/bin/env python import json import csv from prompt import float_input FILENAME_PREFIX = '56_track_product' def load_json(): try: with open(f'{FILENAME_PREFIX}.json') as fp: return json.loads(fp.read()) except FileNotFoundError: return [] def save_json(data): with open...
#!/usr/bin/env python # -*- coding: utf-8 -*- num1 = int(input("What is the first number? ")) num2 = int(input("What is the second number? ")) add_str = f"{num1} + {num2} = {num1 + num2}" sub_str = f"{num1} - {num2} = {num1 - num2}" mul_str = f"{num1} * {num2} = {num1 * num2}" div_str = f"{num1} / {num2} = {num1 // n...
#!/usr/bin/env python # -*- coding: utf-8 -*- n = int(input("Enter the number of inputs: ")) numbers = [] for i in range(n): try: num = int(input("Enter a number: ")) numbers += [num] except: pass print(f"The total is {sum(numbers)}.")
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from records import print_records names = [x.strip() for x in sys.stdin.readlines()] names.sort() column_name = f"Total of {len(names)} names" records = [{ column_name: x } for x in names] print(print_records(records, [column_name]))
a=[1,2,3,4,5,6,7,8,9] b=[] # for i in a: # if i%2==0: # b.append(i) # print(b) # alternative_b=[i for i in a if i%2==0] # print(alternative_b) # a=[(0,'sheldon'),(1, 'penny')] # for e in a: # print(e[1]) # for e in a: # print(e) # a=[0,1,2] # b=[2,4,6] # c=[] # for i in a: # for x in b: # ...
import nltk class Analyzer(): """Implements sentiment analysis.""" def __init__(self, positives, negatives): """Initialize Analyzer.""" self.positives=set() self.negatives=set() with open(positives) as lines: for line in lines: if line.starts...
from typing import List def calculate_simple_moving_average(values: [List[float], int]) -> float: if values == -1: return -1 return _get_average(values) def _get_average(my_list: List[float]) -> float: return sum(my_list) / len(my_list)
# coding=utf-8 import random # # s = int(random.uniform(1, 10)) # # print(s) # m = int(input('输入整数:')) # while m != s: # if m > s: # print('大了') # m = int(input('输入整数:')) # if m < s: # print('小了') # m = int(input('输入整数:')) # if m == s: # print('OK') # break ...
''' Benutzer gibt Wörter ein bis er 0 eingibt Dann das längste Wort mit der Zahl der Buchstaben retournieren Version1: ''' max = None user_input = '1' while user_input != str(0): user_input = input('Wort: ') if max is None or len(user_input) > max: max_wort = user_input max = len(us...
''' jedes Element bearbeiten ''' a=[ 1, 2, 3, ] for element in a: print(element) a = 'einen Text' for buchstabe in a: print(buchstabe) print(a[1]) a[1] = 'u'
''' einlesen von CSV File with open("daten.csv", "r") as file: lines = file.readlines() print(lines) am ende von with wird die Datei zugemacht sobald das Python Programm geschloßen ist wird die Datei auch geschloßen ''' import csv from pprint import pprint with open("daten.csv", "r") as file:...
import math from datetime import datetime # Ask user for an integer with the given prompt. def getInt(prompt): while True: i = input(prompt) try: i = float(i) except ValueError: continue return i # Attempt to convert given value to an integer. def tryToInt(i...
M = [[False, True, True, False, False], [True, False, True, False, False], [True, True, False, True, False], [False, False, True, False, False], [False, False, False, False, False]] n = len(M) def cycle(M): ways = [] for start in range(n): for j in range(n): if M[start][...
from math import sqrt class Compl: def __init__(self, x=0, y=0): self.x = x self.y = y def __str__(self): if self.y == 1: return f'{self.x} + i' elif self.y == -1: return f'{self.x} - i' elif self.y > 0: return f'{self.x} + {self.y}i...
class SkipIterator: def init(self, wrapped): self.wrapped = wrapped # Информация о состоянии self.offset = 0 def next(self): if self.offset >= len(self.wrapped): # Завершить итерации raise StopIteration else: ...
'''Если записать числа от 1 до 5 английскими словами (one, two, three, four, five), то используется всего 3 + 3 + 5 + 4 + 4 = 19 букв. Сколько букв понадобится для записи всех чисел от 1 до 1000 (one thousand) включительно?''' d = {0: '',1:'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eig...
d = {} def update_dictionary(d, key, value): if key in d.keys(): d[key] = [value] elif key * 2 in d.keys(): d[key*2] = [value] else: d[key*2] = [value] return(d) update_dictionary(d, 8, 3) print(d[16])
tabuleiro =[[1,1,1,1],[0,1,1,0],[0,1,0,1],[0,1,9,1],[1,1,1,1]] #tabuleiro =[[1,1,1,1],[0,1,1,0],[9,1,0,1],[0,1,0,1],[1,1,1,1]] path = [] encontrado = None for i in range(len(tabuleiro[0]) +1): #loop que percorre o eixo y for j in range(len(tabuleiro) - 1): #loop que percorre o eixo x if tabuleir...
from random import randint from sys import argv ''' Utilizes the Fisher-Yates shuffle Alogirthm Desc: This alogrithm takes the index value and swaps it with the current value until the end of the list https://www.geeksforgeeks.org/python-ways-to-shuffle-a-list/ ''' def rearrange_word(input): # Initializes a list...
""" An avid hiker keeps meticulous records of their hikes. During the last hike that took exactly steps steps, for every step it was noted if it was an uphill, U, or a downhill, D step. Hikes always start and end at sea level, and each step up or down represents a 1 unit change in altitude. We define the following term...
""" https://www.hackerrank.com/challenges/new-year-chaos/problem It's New Year's Day and everyone's in line for the Wonderland rollercoaster ride! There are a number of people queued up, and each person wears a sticker indicating their initial position in the queue. Initial positions increment by 1 from 1 at the front...
''' Cookie Monster can eat either 1, 2, or 3 cookies at a time. If he were given a jar of cookies with `n` cookies inside of it, how many ways could he eat all `n` cookies in the cookie jar? Implement a function `eating_cookies` that counts the number of possible ways Cookie Monster can eat all of the cookies in the ja...
""" https://www.hackerrank.com/challenges/repeated-string/problem Lilah has a string, , of lowercase English letters that she repeated infinitely many times. Given an integer, n, find and print the number of letter a's in the first n letters of Lilah's infinite string. For example, if the string s='abcac' and n=10, ...
''' Input: a List of integers where every int except one shows up twice Returns: an integer ''' # return the integer that only shows up once in the array def single_number(arr): result = arr[0] # do XOR of all elements for i in range(1, len(arr)): result = result ^ arr[i] return result # XOR...
""" Python 1 - DAT-119 - Spring 2019 Joe Holleran 03/27/2019 In-Class Assignment - Week 8 - To-Do List """ # Lists for to-do and finished or completed items to_do_list = [] finish_list = [] # Welcome user to the to-do list application print("--------------------------------------") print("Welcome to the to-do list app...
# -*- coding: utf-8 -*- from time import* num = int(input("ingresa un numero: ")) contador = len(str(num)) print ("el numero tiene %s digitos" % (contador)) sleep(20)
# Use words.txt as the file name fname = raw_input("Enter file name: ") try: fh = open(fname) except: print "The file can not be opened:", fname exit() for line in fh : line = line.rstrip().upper() print line
import re regex = r"<\w+>" nums = r"[0-9]" word = input() matches = re.findall(regex, word, re.MULTILINE | re.IGNORECASE) if matches: for match in matches: carats = sum(map(int, re.findall(nums,match))) print(f"Found {carats} carat diamond") else: print(f"Better luck next time")
count = int(input()) colorDic = dict() for i in range(count): parts = input().split(" -> ") color = parts[0] items = parts[1].split(",") if colorDic.__contains__(color): for item in items: if item == "": continue if colorDic[color].__contains__(item): ...