text
stringlengths
37
1.41M
from random import randint print(''' Игра "Виселица". Тема игры: Методы списков в Python. ''') words = { 'append':'Добавляет элемент в конец списка', 'extend':'Расширяет список list, добавляя в конец все элементы списка L', 'insert':'Вставляет на i-ый элемент значение x', 'remove':'Удаляет первый элемен...
counter = 0 total = 0 while (True): try: a = input("Enter the number: ") a = float(a) total = total + a counter = counter + 1 except: if (a == "done"): break else: print("Invalid input") continue average = total/counter print(total,counter,average)
t=input("Enter no. of files do you want to merge\n") filenames =[] print "Enter file names" for i in range(1,t+1) : filenames.append(raw_input()) with open('new.txt', 'w') as outfile: for fname in filenames: with open(fname) as infile: for line in infile: outfile.write(line)
from zipfile import ZipFile # try: # arquivo = ZipFile("banco.zip") # arquivo.extractall(path="banco") # arquivo.close() # except Exception as ose: # print("Algum problema ao ler o arquivo {}".format(ose.filename)) try: arquivo = ZipFile('files.zip') arquivo.extractall(path="files") except FileNotFoundError: p...
class ContaBancaria: quant = 0 def __init__(self, agencia: str, conta: str): self.__agencia = agencia self.__conta = conta self.__saldo = 0 ContaBancaria.quant += 1 def setAgencia(self, agencia: str): if agencia: self.__agencia = agencia def getAg...
def divide(x, y): try: result = x/y except Exception: print("Divisão por zero!") else: print("Resultado:", result) finally: print("Executando o bloco finally") # divide(2,2)
def current_value(one=0,two=0,five=0,ten=0,twenty=0,fifty=0,hundred=0,two_hundred=0): return one + two * 2 + five * 5 + ten * 10 + twenty * 20 + fifty * 50 + hundred * 100 + two_hundred * 200 '''combo_num, combo_array = coin_sums() print(combo_num) for row in combo_array: print(row)''' def c_sums...
num_to_word = {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:"seventeen", 18:"eighteen", 19:"nineteen", 20:"twenty", 30:"thirty", 40:"forty", 50:"f...
#!/usr/bin/env python3 # Test for time. import time result = 0 start = time.time() for i in range(1000000): result = i + result end = time.time() print(start - end, '\nresult is', result) time.strftime
#!/usr/bin/env python3 # Calculate Armstrong number. # 判断是否为阿姆斯特朗数返回Ture或False def decArm(num): n = decNum(num) s = 0 strnum = str(num) for c in strnum: s = s + pow(int(c), n) if s == num: return True else: return False # 判断是几位数 def decNum(num): n = 1 while num ...
#!/usr/bin/env python3 # This is a program for count words in hamlet. def getTxt(): txt = open("hamlet.txt", "r").read() txt = txt.lower() for ch in "~!@#$%^&*()_+{}|:<>?`-=[];',./": txt = txt.replace(ch, " ") return txt def countWords(ls): count = dict() for word in ls: count[...
#Christopher Seven #DU ID - 873571051 #This program takes in a file, or multiple files, as well as the flags -c, -z, and -l to then count the frequency of each letter appearing in said file(s). import sys import string def add_frequencies(d, file, remove_case): #This function is accessed through the main(...
import count import sys import csv def count_to_csv(): #This function writes the dictionary created from flags() in count.py into a csv file. vals = [] for val in sys.argv: vals.append(val) d = {} d = count.flags(vals) for i in vals: if i.endswith(".csv"): ...
# coding: utf-8 # # Get the treasures in the maze with Djikstra ! # ### 1 ) Create a maze with random walls. Probability about ~ 0.8 for having walls. # ### 2 ) There are treasures in the maze. We have to get them as fast as possible => salesman traveller problem # ### 3 ) Tournament between 2 players in the maze w...
class StationarityCheck: '''This class is used to test for stationarity of passed time series dataset. The following tests are invoked from pdmarima library and used to test the time series for the trend: Kwiatkowski–Phillips–Schmidt–Shin (KPSS); Augmented Dickey Fuller (ADF); ...
import csv SALARIES_PATH = 'salaries.csv' SALARIES_SUMMARY_PATH = 'salaries_summary.csv' with open(SALARIES_PATH) as file: reader = csv.reader(file) next(reader) salaries = [int(row[1]) for row in reader] header = ['TYPE', 'SALARY'] with open(SALARIES_SUMMARY_PATH, 'w') as file: writer = csv.writer(...
numbers_string = input('Hello, please write your numbers and press enter to confirm: ') numbers = numbers_string.split(',') numbers_list = [] for number in numbers: numbers_list.append(int(number.strip())) print('List:', numbers_list) # numbers_list = [int(number.strip()) for number in numbers_string]
text = input('Give me any string: ') if text.isdigit(): print('Numeric') elif text.isalpha(): print('Letters Only') else: print('Mixed')
String01 = 'Bratislava' String02 = 'Budapest' print('Common characters:', set(String01) & set(String02)) print('Unique characters:', set(String01) - set(String02))
number = int(input('Please enter your number: ')) result = 0 while number > 0: result += number ** number number -= 1 print('The result is:', result)
def vertical_histogram(sequence, bar_width=1): max_row = max(sequence) max_row_length = len(str(max_row)) for level in range(max_row, 0, -1): row = f'{level:>{max_row_length}}|' for item in sequence: fill_symbol = '*' if item >= level else ' ' row += f' {fill_symbol ...
def gcd(a, b): while True: quotient, remainder = divmod(a, b) if remainder == 0: return b a, b = b, remainder print(gcd(414, 78)) print(gcd(414, 49))
#Ryan Jones #4/13/18 #wordSort.py listName = input('Enter some words: ').split(' ') listName.sort() for item in listName: print(item)
# Julia is planning a vacation and has a list of cities she wants to visit. She doesn't have a map of the area, but she does have some data that will help her determine whether there is a road connecting all the cities she wants to visit. The data comes in the form of two arrays. Each of the first array's elements is a...
import sqlite3 as sql import pandas as pd conn = sql.connect('rpg_db.sqlite3') print('Connection: ', conn) curs = conn.cursor() print('Cursor: ', curs, '\n') # Question 1: How many total Characters are there? query = ''' SELECT count (distinct character_id) FROM charactercreator_character; ''' result = curs.execute...
import sys counter = 1 s = input().strip() for letter in s: if (letter.isupper()): counter +=1 print(counter)
from tkinter import * root = Tk() root.title('Place method') l1 = Label(root, text='Physics') l1.place(x=10, y=10) e1 = Entry(root, bd=2) e1.place(x=70, y=10) l2 = Label(root, text='Maths') l2.place(x=10, y=50) e2 = Entry(root, bd=2) e2.place(x=70, y=50) l3 = Label(root, text='Total') l3.place(x=10, y=150) e3 = En...
#!/usr/bin/env python3 # criando uma lista e populando usando um range numbers = [] for i in range(10): numbers.append(i) print(numbers) # fazendo o mesmo com list_comprehension new_numbers = [i for i in range(10)] print(new_numbers) print() # Operacao matematica numbers_multiplied = [i * 2 for i in range(10)]...
from tkinter import * root = Tk() root.title("Grid Method") b = 0 for r in range(6): for c in range(6): b+=1 Button(root, text=str(b), borderwidth=1).grid(row=r, column=c) root.mainloop()
#!/usr/bin/env python3 S = [x**2 for x in range(10)] V = [2**i for i in range(13)] M = [x for x in S if x % 2 == 0] print(S) print(V) print(M)
#!/usr/bin/env python3 kilometer = [39.2, 36.5, 37.3, 37.8] feet = [3280.8399 * x for x in kilometer] print(feet) num = [x + 1 if x >= 120000 else x + 5 for x in feet] print(num)
#!/usr/bin/env python3 import functools @functools.lru_cache(maxsize=4) def fibonacci(num): print(f'Calculating Fibonacci ({num})') if num < 2: return num else: return fibonacci(num -1) + fibonacci(num - 2) fibonacci(10) print('-' * 30) fibonacci(5) print('-' * 30) fibonacci(8) print('-...
#!/usr/bin/env python3 # loops aninhados numList = [] for x in [10,20,30]: for j in [2,4,6]: numList.append(x *j) print(numList) # comprehension numList2 = [x * y for x in [10,20,30] for y in[2,4,6]] print(numList2)
#!/usr/bin/env python3 # map(function, iterable) import sys fullname = lambda x: list(map(sys.stdout.write, x)) f=fullname(['Wolfgang ', 'Amadeus ', 'Mozart']) print(f)
#!/usr/bin/env python3 import timeit numbers = range(10) new_list = [] def power_two(numbers): for n in numbers: if n % 2 == 0: new_list.append(n**2) return new_list print(timeit.timeit('power_two(numbers)', globals=globals(), number=100000)) print() #list comprehension print(timeit.t...
from tkinter import * root = Tk() root.title("Label and fill") Label(root, text="Sufficient Width", fg="white", bg="purple").pack() Label(root, text="Width of x", fg="white", bg="green").pack(fill='x') Label(root, text="Height of y", fg="white", bg="black").pack(fill='y', side=LEFT) root.mainloop()
import math def solve_quadratic_equation(a, b, c): discr = b ** 2 - 4 * a * c if a == 0: print('Constant a can not be equal to 0') elif discr > 0: x1 = (-b + math.sqrt(discr)) / (2 * a) x2 = (-b - math.sqrt(discr)) / (2 * a) return x1, x2 elif discr == 0: x1 = -...
""" Problem Description Given a number A. Find the factorial of the number. Assume Python doesn't support BigInt and the maximum int storage for 64 bit computer is 2^64. So large factorial inputs will fail with this upperbound if we keep the result in an int. Problem Constraints 1 <= A <= 100 Input Format First a...
""" Find the occurrences of pattern P in string S Un-optimized naive algorithm Given a string S = "missisippi", find the occurrences of pattern "isip" while i < len(S) Loop p in P: if p matches s[i], increment i if p doesn't match s[i], break incr i """ def pattern_match(S, P): matches ...
""" Merge Sort - Bottom Up Worst/Best Case - O(N LogN) Space - O(N) # Algorithm MergeSort(arr, i, j) if (i == j): return else: mid = (i + j) // 2 MergeSort(arr, i, mid) MergeSort(arr, mid+1, j) MERGE(arr, i, mid, mid+1, j) return arr # Merge items of size 1 # merge items of size 2 next # merge items of s...
""" Sort the Files Lexicographically # Problem Your task is given N to return the sorted lexicographically list of file names. N is in the range [1, 1,000,000]. In 40% of the test cases N will be no higher than 1,000. If N if higher than 1,000 return just the first 1,000 file names. SAMPLE INPUT 16 SAMPLE OUTPUT ...
""" Number of Visible Nodes There is a binary tree with N nodes. You are viewing the tree from its left side and can see only the leftmost nodes at each level. Return the number of visible nodes. Note: You can see only the leftmost nodes, but that doesn't mean they have to be left nodes. The leftmost node at a leve...
""" Insertion Sort Worst Case - O(N^2) - n-1 + n-2 + ... 2. 1 = N(N+1)/2 Best Case - O(N) Space - O(1) # Algorithm Sorting is typically done in-place, by iterating up the array, growing the sorted list behind it. At each array-position, it checks the value there against the largest value in the sorted list (which h...
""" # Problem A sequence of numbers is called zigzag sequence if the difference between two successive numbers strictly alternate between positive and negative. Fo e.g: 1,7,4,9,2,5 is a zigzag sequence because the difference (6, -3, 5, -7, 3) are alternating between positive or negative Given a sequence of integers,...
# print all the powers of 2 between 1 and n inclusive using recursion def power_of_2(n): if n == 0: return 0 elif n == 1: print(1) return 1 else: prev = power_of_2(n/2) print(2 * prev) return 2 * prev power_of_2(8)
""" Cover the Border Air traffic control of one country wants to check how well its radars are covering the border. There are plenty of radars each covering one contiguous strip of the border. Some radars' coverage strips overlap. Because of the numerous overlaps it is hard for the air traffic control managers to comp...
""" Queue Make sure to use the deque method from collections class for queue operations. Using an array with array.pop(0) is a O(n) operation You can also use Queue class but as a data structure it's cimply unnecessary. deque() is good enough """ from collections import deque queue = deque() # O(1) # insert new el...
""" Sort the Files Lexicographically - Optimized # Problem Your task is given N to return the sorted lexicographically list of file names. N is in the range [1, 1,000,000]. In 40% of the test cases N will be no higher than 1,000. If N if higher than 1,000 return just the first 1,000 file names. SAMPLE INPUT 16 SAMP...
import torch from torch import optim, nn import torch.nn.functional as F num_epochs = 100 learning_rate = 1e-3 device = torch.device("cuda" if torch.cuda.is_available() else "cpu") test_sentence = """n-gram models are widely used in statistical natural language processing . In speech recognition , phonemes and seque...
# Event: LCCS Python Fundamental Skills Workshop # Date: May 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Purpose: Solution to Q4 page 53 from turtle import * pensize(2) angle = 30 # Initialise a variable called angle to 30 forward(50) # Move forward by 50 units left(a...
# Event: LCCS Python Fundamental Skills Workshop # Date: Dec 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Purpose: Breakout 7.1 Frequency Counters # Q1(h) - solution # Count the number of vowels in a sentence vowels = "aeiou" sentence = input("Enter a sentence: ") chars = {} for cha...
# Event: LCCS Python Fundamental Skills Workshop # Date: Dec 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Purpose: A program to demonstrate the use of functions to read an integer within a specified range # Returns a number between 'lwr' and 'upr' def readIntegerInRangeV1(lwr, upr): ...
# Event: LCCS Python Fundamental Skills Workshop # Date: May 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Purpose: Compute the average of 5 random numbers # Program to multiply two randomly generated numbers import random low = random.randint(1,100) high = random.randint(low,100) ...
# Event: LCCS Python Fundamental Skills Workshop # Date: Dec 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Purpose: Dictionary Programming Exercises 7.1 # Q2(b) solution colours = dict({ 'white': "bán", 'red': "dearg", 'green' : "gorm", 'blue' : "glas", 'black' :...
# Event: LCCS Python Fundamental Skills Workshop # Date: May 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Purpose: A program to demonstrate basic string indexing # Initialise the string pangram = "The quick brown fox jumps over the lazy dog!" # 012345678901234567890123456789012...
# Date: May 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Name: Guessing Game v6 # Purpose: A program to demonstrate sentinel controlled repetition using while # The program also demonstrates the use of nested if statements. # Pay careful attention to the indentation # Description: After a ...
# Event: LCCS Python Fundamental Skills Workshop # Date: Dec 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Purpose: Breakout 6.2 Summing Numbers - Further Activities # Q2 Sum of first N reciprocal def sum_of_reciprocals(n): total = 0 for i in range(1, n+1): total = total...
# Event: LCCS Python Fundamental Skills Workshop # Date: Dec 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Purpose: A program to count (and display) the most frequently occurring words in a text # Breakout 7.1 Frequency Counters # Q2(g) - solution # IMPORTANT: Copy the book into book.txt ...
# Date: May 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Name: Guessing Game v7 # Purpose: A program to demonstrate data validation # Description: This is the exact same as version 6 except the input is validated # Guess Game v7 - while - go again? - data validation import random nu...
# Event: LCCS Python Fundamental Skills Workshop # Date: Dec 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Solution: Programming Exercises 6.3 Q4 # Purpose: A program to validate a password # A valid password is one which is .... # a) between 9 and 12 characters in length and # b) contains...
# Event: LCCS Python Fundamental Skills Workshop # Date: Dec 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Solution to programming exercises 6.1 Q2 # Purpose: A program to find the GCD of any two positive integers # Determines if one number is a factor of the other def isFactor(a1, a2):...
'''multiplication tutor V5 the program should continue until the user gets the correct answer.''' import random n1 = random.randint(0, 12) # Generate the 1st number n2 = random.randint(0, 12) # Generate the 2nd number ans = n1*n2 # Calculate the product and store it in 'ans' print("%d * %d" %(n1,n2)) # Dis...
# Event: LCCS Python Fundamental Skills Workshop # Date: Dec 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Purpose: Breakout 7.1 Frequency Counters # Q1(i) - solution # Count the number of words in a sentence (v1) sentence = input("Enter a sentence: ") sent_list = sentence.split() words...
# Event: LCCS Python Fundamental Skills Workshop # Date: Dec 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Purpose: A program to display another silly poem def homework(): # function header print("Jack loves to do his homework") print("He never misses a day") print("He even love...
# Event: LCCS Python Fundamental Skills Workshop # Date: May 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Purpose: A program to demonstrate a while loop # Simple while loop # Initialise a loop counter counter = 1 # Loop 10 times while counter <= 10: print("Hello World") # Dis...
# Event: LCCS Python Fundamental Skills Workshop # Date: May 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Purpose: Turtle Graphics - match the code to the shape from turtle import * # Question: Which shape does this code draw? x=50 y=25 forward(2*x+y) left(90) forward(x+2*y) left(...
# Event: LCCS Python Fundamental Skills Workshop # Date: May 2023 # Author: Computer Science, PDST # eMail: computerscience@pdst.ie # Purpose: Turtle Graphics - Further Activities # Python Manual, page 17, Further Activites - Exercise 3 from turtle import * # import the turtle graphics library #draws a 50 x 50 square...
# Event: LCCS Python Fundamental Skills Workshop # Date: Dec 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Purpose: Dictionary Programming Exercises 7.1 # Q1(h) solution car = dict( { 'reg': "131 CN 6439", 'make': "Audi", 'model' : "A6", 'year' : 2013, 'kms' : 5273...
# Event: LCCS Python Fundamental Skills Workshop # Date: Dec 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Purpose: A program to demonstrate how to build a dictionary # Version 2a. A dictionary to store multiple results for a student results = {} name = input("Enter student name: ") ...
# Event: LCCS Python Fundamental Skills Workshop # Date: May 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Purpose: To demonstrate syntax errors relating to lists # To extend thinking in relation to list slicing range errors suits = ['Hearts','Diamonds','Spades','Clubs'] cardFaces = ['Ace...
# Event: LCCS Python Fundamental Skills Workshop # Date: Dec 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Purpose: A program to demonstrate the use of parameters and arguments # 'personName' is a parameter in the function called 'homework' # Function definition for 'homework' def homewor...
'''Create a python program to secure an existing password by replacing a set of characters with the corresponding 'password-secure' character (Provided as tuple). Example: SECURE = (('s', '$'), ('and', '&'), ('a', '@'), ('o', '0'), ('i', '1'), ('I', '|')) Input: password = "Indians1...
#General Assembly Lecture 3 #Created joseph solway 9/10/2014 #Last updated joseph solway 9/10/2014 #Exercise 3 #Lab: Munging data #1. Count the number of each instance in index 3 (bachelors, hs-grad, etc) #2. Count the number of each combinatino in index 3 and index 10 (gender) #3. Find the average hours per week (ind...
# FUNCTION # f(x) = 2x + 2 # f(3) = 2(3) + 2 = 8 # Cara Bikin Function def hello(): print('Hello World') hello() # f(x) = x ^ 2 def kuadrat(x): print(x ** 2) kuadrat(2) kuadrat(3) def pangkat(angka1, angka2): print(angka1 ** angka2) pangkat(2,3) pangkat(2,10) pangkat( float(input('Ketik angka 1...
""" @file sobel_demo.py @brief Sample code using Sobel and/or Scharr OpenCV functions to make a simple Edge Detector """ import sys import cv2 as cv def main(argv): ## [variables] # First we declare the variables we are going to use window_name = ('Sobel Demo - Simple Edge Detector') scale = 1 del...
import vector as vector from matrix import * import pygame import math import random class Light: """There was darkness, then there was the Light class, then it just needed ambient, diffuse, and specular values.""" def __init__(self, pos, diff, spec): self.pos = pos self.diff = diff sel...
import random def isPrime(n): if (n==1): return False elif (n==2): return True else: for x in range(2,n): if(n % x==0): return False return True def isPrimitive(root, q): if q < root: return False else: va...
# Model import sys from termcolor import colored, cprint import random class Eightball(object): """docstring for Eightball""" def __init__(self): self.name = "" self.answers = [ "It is certain", "It is decidedly so", "Without a doubt", "Yes, definitely", "You may rely on it", "As I see it, ye...
""" ### Code Owner: Alexander Olivero ### Objective: House the logic to solve problem 2 ### Developer Notes: Data found here: https://adventofcode.com/2018/day/2/input """ from pathlib import Path from difflib import ndiff PATH_REFS = Path(__file__).parents[1] / 'references' #-------------------------------...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import time def dtimeit(func): """декоратор для замера времени выполнения""" def timed(*args, **kwargs): ts = time.time() result = func(*args, **kwargs) te = time.time() print("timeit: ", te - ts) return result return timed class ETimer: def __init__(s...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import struct def to_bstring(input: str): bstr = input.encode(encoding="utf-8") str_len = len(bstr) bdata = b"" bdata += struct.pack("<I", str_len) bdata += bstr return bdata def from_bstring(bdata): str_len = struct.unpack("<I", bdata[0:4]...
# -*- coding: utf-8 -*- """ Created on Wed Aug 16 10:19:04 2017 @author: Payam """ import datetime # function for reading csv files def readfile(filnam): path = 'C:/Users/Payam/Documents/0_MetroC/0_Final_Projects/Projectj_1/csv/' + filnam + '.csv' print(path) exec(filnam + '= pd.read_csv(pat...
import random def delay(): n=input("Press enter to continue") def wiped_slate(players): for player in players: player['hands']=[] player['suits']=[] player['bets']=[] return players def pprinthand(hand,suit): temphand=hand[:] for i in range(len(temphand)): if temphand...
import numpy as np import matplotlib.pyplot as plt def list_fractions(amount): fractions = [] difference = [] for i in range(1, amount): fractions.append(1/i) return fractions def list_differences(list): difference = [] for i in range(0, len(list)): if list[int(i-1)]: ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jun 17 17:33:57 2020 @author: user """ ''' Count the number of prime numbers less than a non-negative number, n. Example: Input: 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. ''' ''' Use The Sieve of Eratost...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun May 31 14:46:01 2020 @author: user """ ''' There are n soldiers standing in a line. Each soldier is assigned a unique rating value. You have to form a team of 3 soldiers amongst them under the following rules: Choose 3 soldiers with index (i, j, k...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jun 4 19:14:50 2020 @author: user """ ''' Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9] Note:...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri May 22 00:38:54 2020 @author: user """ ''' Could be done in one-line expression, but if there is a function call, I see no point as one-lineers still harder to read ''' def disemvowel(string): vowels=['a','e','i','o','u'] #classic English vowels, '...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 28 12:01:30 2020 @author: user """ ''' Complete the function scramble(str1, str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false. Notes: Only lower case letters will be used (a-z). No ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue May 26 15:50:12 2020 @author: user """ ''' Write a function called sumIntervals/sum_intervals() that accepts an array of intervals, and returns the s um of all the interval lengths. Overlapping intervals should only be counted once. Intervals Inter...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 28 12:41:27 2020 @author: user """ ''' The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers: maxSequence([-2, 1, -3, 4, -1, 2, 1, -5, 4]) # should be 6: [4, -1, 2, 1] Ea...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jun 5 17:29:16 2020 @author: user """ ''' Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an enviro...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 25 12:43:28 2020 @author: user """ ''' What is an anagram? Well, two words are anagrams of each other if they both contain the same letters. For example: 'abba' & 'baab' == true 'abba' & 'bbaa' == true 'abba' & 'abbba' == false 'abba' & 'abca...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri May 22 14:49:40 2020 @author: user """ ''' inserts a certain number of words "WUB" before the first word of the song (the number may be zero), after the last word (the number may be zero), and between words (at least one between any pair of nei...
from game.dealer import Dealer class Director: def __init__(self): '''A constructor method for the Director class.''' self.keep_playing = True self.score = 300 self.dealer = Dealer() def start_game(self): ''' The start_game method for the Director class. Continues the g...
secretWord = "giraffe" clues = ["", "animal in movie madagascar", "large animal", "animal with longest neck", "HAHA TOUGHT IT WAS A CLUE, YOU LOST"] guess = "" guessCount = 0 while guess != secretWord: print("GUESS ", guessCount, " :-") print("") guess = str(input("Enter guess: ")) if guess == secretWo...
import csv from csv import writer import sys import os def save_file(user,wahana,pembelian,penggunaan,tiket,refund,ks): with open(input('Masukkan nama File user: '), 'w', newline='') as write_obj: csv_writer = writer(write_obj) for row in user: csv_writer.writerow(row) #done with o...
""" File: random_numbers.py ----------------------- This program prints a series of random numbers in the range from MIN_RANDOM to MAX_RANDOM, inclusive """ import random def main(): """ You should write your code for this program in this function. Make sure to delete the 'pass' line before starting to wr...
def reverse(x): s = cmp(x, 0) print(s) i = int(str(x)[::-1]) print(i) return i*s * (i < 2**31) # # print(reverse(-214748364787)) # import operator # def reverse(x): # print(operator.lt(x, 0)) # # print(int(str(x)[:0:-1])) # # return i*s *(i<2**31) # print(reverse(-124)) # def reverse(x): # s = ...
#PLEASE VISIT: www.pythonforphysics.blogspot.com #Created by: Oriol Frigola #Year: 2013 #THE PROGRAM IS DISTRIBUTED IN THE HOPE THAT #...IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. from __future__ import division, print_function from vpython import * import math scene.width = 700 scene.height = 600 scene.title = 'THR...