text
stringlengths
37
1.41M
''' 7562 λ‚˜μ΄νŠΈμ˜ 이동 μ•Œκ³ λ¦¬μ¦˜: 1. λ‚˜μ΄νŠΈκ°€ 갈 수 μžˆλŠ” 8λ°©ν–₯의 μ’Œν‘œλ₯Ό μ •μ˜ν•˜κ³ , μ΅œμ†Œμ΄λ™μ΄λ―€λ‘œ bfsμ‚¬μš© 2. bfs의 μ’…λ£Œ 쑰건 μ„€μ •ν•  생각을 λͺ»ν•΄λƒˆλ‹€ --> νμ—μ„œ λΉΌλ‚Έ 값이 κ°™μœΌλ©΄ μ’…λ£Œν•΄λ„λœλ‹€ ''' from collections import deque def bfs(x, y): q = deque() q.append([x, y]) chess[x][y] = 1 while q: x, y = q.popleft() if x == dox and y == doy: ...
''' 10867 쀑볡 λΉΌκ³  μ •λ ¬ν•˜κΈ° 1. 쀑볡을 μ—†μ• μ•Ό ν•˜λ‹ˆκΉŒ dict μžλ£Œν˜•μ„ μ‚¬μš© (set ν•¨μˆ˜λ₯Ό μ“°λ €λ‹€κ°€ λͺ» 썼닀) +) sorted(list(set(array))) 둜 set을 list둜 λ³€ν™˜ν•˜κ³  κ·Έ λ‹€μŒμ— μ •λ ¬ν•˜λ©΄ λœλ‹€ ''' import sys N = int(input()) array = list(map(int, sys.stdin.readline().split())) dict = {} for i in array: if i not in dict.keys(): dict[i] = 1 array = sorte...
''' 1439 λ’€μ§‘κΈ° μ•Œκ³ λ¦¬μ¦˜: 1. μž…λ ₯받은 λ¬Έμžμ—΄μ„ 0을 κΈ°μ€€μœΌλ‘œ λΆ„λ¦¬ν•˜κ³ , 1을 κΈ°μ€€μœΌλ‘œ λΆ„λ¦¬ν•΄μ„œ 각각 list에 λ„£λŠ”λ‹€ 2. 각 리슀트의 κΈΈμ΄λŠ” 숫자λ₯Ό κ°™κ²Œ λ§Œλ“€λ„λ‘ 뒀집을 λ•Œμ˜ μ—°μ‚° νšŸμˆ˜μ΄λ‹€ 3. λ”°λΌμ„œ, 길이가 짧은 리슀트λ₯Ό κ³ λ₯΄λ©΄ λœλ‹€ ''' s = input() zerolist = s.split('1') onelist = s.split('0') # λ¦¬μŠ€νŠΈμ•ˆμ— 빈 λ¬Έμžμ—΄λ“€μ„ μ œκ±°ν•˜λŠ” 방법 zerolist = [v for v in zerolist if v] onelist = [v for v in onelist if ...
# Find pairs in an integer array whose sum is equal to 10 # Bonus: do it in linear time import sys def pairs_sum_to_10(arr, n, sum): m = [0] * 1000 # Store counts of all elements in map m for i in range(0, n): m[arr[i]] m[arr[i]] += 1 twice_count = 0 # Iterate through each el...
# Prints out the binary form of an integer def conv_to_bin(num): return bin(num) print conv_to_bin(1) print conv_to_bin(2) print conv_to_bin(3) print conv_to_bin(4) def int_to_bin_string(i): if i == 0: return "0" s = '' while i: if i & 1 == 1: s = "1" + s else: ...
from datetime import date user_vm="" logged_in = False def login(): username=input("Username:# ") password=input("Password:# ") # Logging in module with open('user.txt','r') as users: for row in users: if username and password in row: print ("Login successful!") ...
import unittest from app.models.game import Game from app.models.player import Player class TestGame(unittest.TestCase): def setUp(self): self.player1 = Player("Katie", "paper") self.player2 = Player("Tom", "rock") self.player3 = Player("Liam", "rock") self.player4 = Player("Maria...
""" Task. You are given a binary tree with integers as its keys. You need to test whether it is a correct binary search tree. Note that there can be duplicate integers in the tree, and this is allowed. The definition of the binary search tree in such case is the following: for any node of the tree, if its key is π‘₯, th...
""" Task. You have a program which is parallelized and uses 𝑛 independent threads to process the given list of π‘š jobs. Threads take jobs in the order they are given in the input. If there is a free thread, it immediately takes the next job from the list. If a thread has started processing a job, it doesn’t interrupt ...
""" Task. Given 𝑛 gold bars, find the maximum weight of gold that fits into a bag of capacity π‘Š. Input Format. The first line of the input contains the capacity π‘Š of a knapsack and the number 𝑛 of bars of gold. The next line contains 𝑛 integers 𝑀0, 𝑀1, . . . , π‘€π‘›βˆ’1 defining the weights of the bars of gold. C...
""" Task. Given two integers π‘Ž and 𝑏, find their greatest common divisor. Input Format. The two integers π‘Ž, 𝑏 are given in the same line separated by space. Constraints. 1 ≀ π‘Ž, 𝑏 ≀ 2 Β· 109. Output Format. Output GCD(π‘Ž, 𝑏). """ def get_gcd_naive(a, b): gcd = 1 for d in range(2, min(a, b) + 1): ...
""" Task. Construct the Burrows–Wheeler transform of a string. Input Format. A string Text ending with a β€œ$” symbol. Constraints. 1 ≀ |Text| ≀ 1 000; except for the last symbol, Text contains symbols A, C, G, T only. Output Format. BWT(Text). """ def bwt(text): n = len(text) cycle_matrix = [] s = text ...
""" Input Format. The first line contains an integer 𝑑. The second line contains an integer π‘š. The third line specifies an integer 𝑛. Finally, the last line contains integers stop1,stop2, . . . ,stop𝑛. Output Format. Assuming that the distance between the cities is 𝑑 miles, a car can travel at most π‘š miles on a ...
""" Task. In this task your goal is to implement a hash table with lists chaining. You are already given the number of buckets π‘š and the hash function. It is a polynomial hash function where 𝑆[𝑖] is the ASCII code of the 𝑖-th symbol of 𝑆, 𝑝 = 1 000 000 007 and π‘₯ = 263. Your program should support the following k...
""" Task. Construct the suffix tree of a string. Input Format. A string Text ending with a β€œ$” symbol. Constraints. 1 ≀ |Text| ≀ 5 000; except for the last symbol, Text contains symbols A, C, G, T only. Output Format. The strings labeling the edges of SuffixTree(Text) in any order. """ def max_substring(text_1, te...
C = eval(input("Digite los grados celsius")) F = C + 32 print(C,"Β°C a Fahrenheit es: ", F,"Β°F")
n = int(input('Π’Π²Π΅Π΄ΠΈΡ‚Π΅ количСство элСмСнтов: ')) i = 0 range_number = 1 sum = 0 while i < n: sum += range_number range_number /= -2 i += 1 print(f'Π‘ΡƒΠΌΠΌΠ° {sum}')
from neo4j import GraphDatabase from random import randint import csv def create_subjects(tx, filename, faculty_name): """ Creates subjects and randomly creates Requires relation between them. Subjects are divided into tiers. Subject from higher can only require subjects from lower tier. As a result, ...
print "Mary had a little lamb." print "Its fleece was white as %s." % "snow" print "And everywhere that Mary went." print "." * 20 # Repeats "." 20 times (including the first time!) char1 = "C" char2 = "h" char3 = "e" char4 = "e" char5 = "s" char6 = "e" char7 = "b" char8 = "u" char9 = "r" char10 = "g" char11 = "e" cha...
import socket import sys #Create socket object try: socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error: print("Could not create socket") #Use host that user input script,host = sys.argv #Connect to a remote socket at specified host address socket.connect((host, 6869)) #Initial response ...
from random import randrange from input_number_between import input_number_between def play(): START_MONEY = 100 MIN_MONEY_TO_WIN = 200 FACTOR_WIN = 2 money = START_MONEY print "At any time, bet 0 to quit. Quit above %d to win 1/%d of your coins in money" % (MIN_MONEY_TO_WIN, FACTOR_WIN) ...
from binarysearchtree import BinarySearchTree def testBST(): bst1 = BinarySearchTree() n=int(raw_input("Enter number of elements: ")) for i in range(n): bst1.insertElement(int(raw_input())) print "INORDER:" bst1.inorderTraverse(bst1.root) print print "PREORDER:" bst1.preorderTra...
import hashlib file = open('words.txt','r') content = file.readlines() file.close() word_list = [] for line in content: line = line.strip() word_list.append(line) username= input("Username: ") realm = "Boutique Cassee" #178ec06684f4d2ca85f4d704eff5ac1d hashToFind = input("Password hash: ") for word in word_lis...
#!/usr/bin/python3 #input number number = 112345678911234566 #count the twos Number2 = number.count(2) #print the number of 2s print(β€˜There are %d twos in %d.’ % (Number2,number))
import pandas as pd """Plan Part 1: The user can log how many reps/km they did. IF they don't wish to log the day then the result given will be 0 for the exercises that day. after 3 days have been logged the program will stop and congratulate the user on doing their weeks worth of exercise. Part 2: the week l...
import json from collections import defaultdict class Search(): """ Class that is used to find documents that contain given terms. Attributes: doc2id : dict(str, int) dictionary that maps document celex numbers to ids id2doc : dict(int, str) dictionay that maps ids ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def kthSmallest(self, root: TreeNode, k: int) -> int: count = 0 ksmall = -9999999999 # store...
# -*- coding: utf-8 -*- """ Created on Sat Aug 28 11:00:37 2021 @author: KushagraK7 """ print("You will be asked to enter two numbers.") print("Then the computer will swap the values of the variables storing them") A = int(input("Enter a number to store in variable 'A' ")) B = int(input("Enter a num...
from datetime import datetime from math import atan2, sqrt from pathlib import Path from typing import List, Tuple, Dict DATA_PATH = Path('data.txt') def read_data_file() -> List[Tuple[int, int]]: """Reading points from a file. Returns: List[Tuple[int, int]]: List of points, e.g. [(x,y)] """ ...
# Neural Network - Simple example import numpy as np import pickle round_digits = 4 # SIGMOID FUNCTION def sigmoid(x): # activation function: f(x) = 1 / (1 + e^(-x)) return round(1 / (1 + np.exp(-x)), round_digits) # SIGMOID DERIVATIVE FUNCTION def deriv_sigmoid(x): # Derivative of sigmoid: f'(x) = f(x)...
from measurement.measures import Speed from . import activity class VO2: _value: float """float: Estimated VO2 reserve value """ def __init__(self, o2_cost_horiz: float, o2_cost_vert: float, speed: Speed, grade = 0.0): """Initializes instance. Args: o2_cost_horiz (float): ...
colors = ["red", "green", "blue", "purple"] ratios = [0.2, 0.3, 0.1, 0.4] for i, color in enumerate(colors): ratio = ratios[i] print("{}% {}".format(ratio * 100, color)) lst = ['A','B','C','D'] print({k: v for v, k in enumerate(lst)}) dictionary = dict(zip(colors, ratios)) print(dictionary) for i in colors:...
''' Practice: Companies and Employees Instructions Create an Employee type that contains information about employees of a company. Each employee must have a name, job title, and employment start date. Create a Company type that employees can work for. A company should have a business name, address, and industry type. ...
def buildCoder(shift): """ Returns a dict that can apply a Caesar cipher to a letter. The cipher is defined by the shift value. Ignores non-letter characters like punctuation, numbers, and spaces. shift: 0 <= int < 26 returns: dict """ ### TODO import string CodeDict = {} f...
def findBestShift(wordList, text): """ Finds a shift key that can decrypt the encoded text. text: string returns: 0 <= int < 26 """ ### TODO bestShift = 0 bestCorrectWordNumber = 0 words = text.split() for shift in range(26): correctWordNumber = 0 for word in wor...
from math import * class User_interface: def __init__(self, conf_file_name): self.area = [] self.activators = [] # +y forward, +x right, [cm] self.parse_conf(conf_file_name) self.pressed = [False]*len(self.activators) self.activation = 0 d...
# We have a list of points on the plane. Find the K closest points to the origin (0, 0). # # (Here, the distance between two points on a plane is the Euclidean distance.) # # You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in.) # # # # Example 1: # # Inpu...
# Given a non-empty array of integers, every element appears twice except for one. Find that single one. # # Note: # # Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? # # Example 1: # # Input: [2,2,1] # Output: 1 # Example 2: # # Input: [4,1,2,1,2] # Output: 4 ...
# Design a data structure that supports adding new words and finding if a string matches any previously added string. # # Implement the WordDictionary class: # # WordDictionary() Initializes the object. # void addWord(word) Adds word to the data structure, it can be matched later. # bool search(word) Returns true if th...
# Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same. # # If possible, output any possible result. If not possible, return the empty string. # # Example 1: # # Input: S = "aab" # Output: "aba" # Example 2: # # Input: S = "aaab" # Output: "" ...
# # 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 environment which could only store integers within the 32-bit signed integer range: # ...
# graph traversal # adjacency List graph = { 1: [2, 3, 4], 2: [5], 3: [5], 4: [], 5: [6, 7], 6: [], 7: [3], } # DFS (depth-first search) # recursive def recursive_dfs(v, discovered=[]): discovered.append(v) # discovered에 정점 μΆ”κ°€ for destination in graph[v]: # κ·Έ μ •μ μ—μ„œ μΆœλ°œν•˜λŠ” 도착지 ...
# Given a reference of a node in a connected undirected graph. # # Return a deep copy (clone) of the graph. # # Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors. # # class Node { # public int val; # public List<Node> neighbors; # } # # # Test case format: # # For simplicity s...
# The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, # # F(0) = 0, F(1) = 1 # F(N) = F(N - 1) + F(N - 2), for N > 1. # Given N, calculate F(N). # # # # Example 1: # # Input: 2 # Output...
# BFS (breath-first Search) graph = { 1: [2, 3, 4], 2: [5], 3: [5], 4: [], 5: [6, 7], 6: [], 7: [3], } def iterative_bfs(start_v): discovered = [start_v] # discovered에 첫 좜발 정점 μ‚½μž… queue = [start_v] # 큐에 첫 좜발 정점 μ‚½μž… while queue: # 큐에 μ•„μ΄ν…œμ΄ ν•˜λ‚˜λΌλ„ μžˆμ„ λ•Œ v = queue.po...
# Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too. # # You need to find the shortest such subarray and output its length. # # Example 1: # Input: [2, 6, 4, 8, 10, 9, 15] # Output: 5 # Exp...
# Given a list of scores of different students, return the average score of each student's top five scores in the order of each student's id. # # Each entry items[i] has items[i][0] the student's id, and items[i][1] the student's score. The average score is calculated using integer division. # # # # Example 1: # # Inp...
# Given a string, your task is to count how many palindromic substrings in this string. # # The substrings with different start indexes or end indexes are counted as different substrings # even they consist of same characters. # # Example 1: # # Input: "abc" # Output: 3 # Explanation: Three palindromic strings: "a", "b...
# Reverse a linked list from position m to n. Do it in one-pass. # # Note: 1 ≀ m ≀ n ≀ length of list. # # Example: # # Input: 1->2->3->4->5->NULL, m = 2, n = 4 # Output: 1->4->3->2->5->NULL # Definition for singly-linked list. # 인덱슀 mμ—μ„œ nκΉŒμ§€λ₯Ό μ—­μˆœμœΌλ‘œ λ§Œλ“€μ–΄λΌ. 인덱슀 m은 1λΆ€ν„° μ‹œμž‘ν•œλ‹€. class ListNode: def __init__(self, val=0,...
# Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. # # Example 1: # # Input: # [ # [ 1, 2, 3 ], # [ 4, 5, 6 ], # [ 7, 8, 9 ] # ] # Output: [1,2,3,6,9,8,7,4,5] # Example 2: # # Input: # [ # [1, 2, 3, 4], # [5, 6, 7, 8], # [9,10,11,12] # ] # Output: [1,2,3,...
# Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK. # # Note: # # If there are multiple valid itineraries, you should return the itinerar...
# Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area. # # # # Example 1: # # # Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]] # Output: 6 # Explanation: The maximal rectangle is shown in...
# Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. # # The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. # # Note: # # Your returned answers (bo...
# # merge sort # # # Sort a linked list in O(n log n) time using constant space complexity. # # Example 1: # # Input: 4->2->1->3 # Output: 1->2->3->4 # Example 2: # # Input: -1->5->3->4->0 # Output: -1->0->3->4->5 # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): se...
# There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of non-empty words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language. # # Example 1: # # Inpu...
# Given a collection of distinct integers, return all possible permutations. # # Example: # # Input: [1,2,3] # Output: # [ # [1,2,3], # [1,3,2], # [2,1,3], # [2,3,1], # [3,1,2], # [3,2,1] # ] import itertools from typing import List class Solution: def permute(self, nums: List[int]) -> List[List[int]]...
# Design a HashMap without using any built-in hash table libraries. # # To be specific, your design should include these functions: # # put(key, value) : Insert a (key, value) pair into the HashMap. # If the value already exists in the HashMap, update the value. # get(key): Returns the value to which the specified key ...
"""Π£Π·Π½Π°ΠΉΡ‚Π΅ Ρƒ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ число n. НайдитС сумму чисСл n + nn + nnn. НапримСр, ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»ΡŒ Π²Π²Ρ‘Π» число 3. Π‘Ρ‡ΠΈΡ‚Π°Π΅ΠΌ 3 + 33 + 333 = 369. """ n = int(input('enter your number ')) nn = int(str(n)*2) nnn = int(str(n)*3) result = n + nn + nnn print(result)
import RPi.GPIO as GPIO from time import sleep class FourSeven: """ Default Pins: Type Seg Pin Reg Pin ---- ------- ------- Digit 1 1 pin 9 pin Digit 2 2 pin 10 pin Digit 3 6 pin 11 pin Digit 4 8 pin 12 pin Seg A 14 pin 1 pin Seg B 16 pin 2 pin ...
# Python program to rename all file # names in your directory import os for count, f in enumerate(os.listdir()): f_name, f_ext = os.path.splitext(f) f_name = f_name.replace(" ","") new_name = f'{f_name}{f_ext}' os.rename(f, new_name)
#Result is 232792560 number = 20 * 19 * 9 * 17 * 8 * 15 * 14 * 13 * 6 * 11 i = 20 while 1: i = i + 20 ok = 1 for x in range(1, 20): if i % x != 0: ok = 0 break if ok == 1: number = i break print "What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?" print ...
""" Experiments with traing comma """ a = [1, 2, 3] print len(a) a2 = [1, 2, 3, ] print len(a2) t = () print type(t), len(t) # <type 'tuple'> 0 t2 = (1,) print type(t2), len(t2) # <type 'tuple'> 1 t3 = (1) print type(t3) # <type 'int'> d = {1: '1', } print len(d) # 1
# Runtime: 32 ms # Memory Usage: 14 MB # Given a column title as appear in an Excel sheet, return its corresponding column number. # For example: # A -> 1 # B -> 2 # C -> 3 # ... # Z -> 26 # AA -> 27 # AB -> 28 # ... # Input: "A" # Output: 1 # Input: "AB" # Output: 28 # Input: "...
# Runtime: 596 ms # Memory Usage: 38.1 MB # Implement the StreamChecker class as follows: # StreamChecker(words): Constructor, init the data structure with the given words. # query(letter): returns true if and only if for some k >= 1, the last k characters queried # (in order from oldest to newest, including this let...
# Runtime: 40 ms # Memory Usage: 13.9 MB # Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add # spaces in s to construct a sentence where each word is a valid dictionary word. Return all such # possible sentences. # Note: # The same word in the dictionary may be reused mult...
# Runtime: 80 ms # Memory Usage: 14.4 MB # Given an array A of non-negative integers, return an array consisting of all the even elements of # A, followed by all the odd elements of A. # You may return any answer array that satisfies this condition. # Input: [3,1,2,4] # Output: [2,4,3,1] # The outputs [4,2,3,1], [2,...
# Author: Zoljargal Gatnumur # Runtime: 40 ms # Memory Usage: 14.3 MB # Given an input string, reverse the string word by word. # Example 1: # Input: "the sky is blue" # Output: "blue is sky the" # Example 2: # Input: " hello world! " # Output: "world! hello" # Explanation: Your reversed string should not contain ...
# Author: Zoljargal Gantumur # Runtime: 20ms # Memory Usage: 13.9MB #Input: x = 1, y = 4 #Output: 2 #Explanation: # 1 (0 0 0 1) # 4 (0 1 0 0) # ↑ ↑ #The above arrows point to positions where the corresponding bits are different. class Solution: def hammingDistance(self, x: int, y: int) -> int: ...
''' Think of an iterator as a generator(fire hose of data) It streams the data to the output and does not return a list but rather an iterable stream of characters ''' class alphabator: def __init__(self, l): self.lst = l self.items = len(self.lst) self.count = -1 def __iter__(self): ...
''' Created on Nov 26, 2013 @author: rduval ''' # !C:\Python33 import random from datetime import datetime import datetime as dt num = "" inputMsg = "Input must be a number." questions = [] def question(num): question_num = num correct = "wrong" b = random.randrange(1, 11) a = random....
''' Created on Jul 30, 2012 @author: rduvalwa2 ''' #!/usr/local/bin/python3 """factorial.py two loops outer loops, variable c counts upward inner loop generates the factorial based on value of counter The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less tha...
#!/usr/local/bin/python3 """program input_counter.py This program breaks input sentences into sets of words and tracks when in order of discovery they were discovered """ discovery = 0 setLength = 0 set_s = set([]) # Empty set dict_d = {} # Empty dict sentence = input("Enter text: ") while len(sentence) > 0...
""" control.py: Creates queues, starts output and worker threads, and pushes inputs into the input queue. """ from queue import Queue from output import OutThread from worker import WorkerThread WORKERS = 10 inq = Queue(maxsize=int(WORKERS * 1.5)) outq = Queue(maxsize=int(WORKERS * 1.5)) ot = Out...
''' Created on Apr 17, 2014 @author: rduvalwa2 ''' import unittest from Py4_Homework13 import sstr, NumberSize class TestSstr(unittest.TestCase): def test_sstr(self): s1 = sstr("abcde") self.assertEqual(s1 << 0, 'abcde') self.assertEqual(s1 >> 0, 'abcde') self.assertEqual(s1 >> 2...
''' https://docs.python.org/2.7/library/mmap.html Created on Apr 26, 2014 @author: rduvalwa2 Here are your instructions: Write a program that creates a: 1. ten megabyte data file in: 2. two different ways 3. time each method The first technique should - create a memory-mapped file and write the data by se...
''' Created on Mar 14, 2013 Question 1: Write an expression that takes two lists of equal length, k and v, and produces a dict where the keys are the elements of k and the corresponding values are the elements of v. >>> keys = ['a', 'b', 'c'] >>> values = [1, 2, 3] >>> dictionary = dict(zip(keys, values)) >>> print di...
#!/usr/local/bin/python3 """ multuple.py formating problem """ myTuple = [(1,1),(2,2),(3,3),(5,5),(7,7),(11,11),(3,101),(101,33)] for element in myTuple: product = element[0] * element[1] n = {'value': product, 'multiplicand': element[0], 'multiplier': element[1]} print("{0[value]:4d} = {0[multiplicand]...
''' CHere are your instructions: Modify the Subscriber.process() method so that the instance counts the number of times the method has been called. If, after processing the current message, it has processed three messages, it unsubscribes itself. Remove the unsubscribe code from the loop at the end of the main prog...
"""This program fileTypeCounter.py reads in: 1. the files in the local directory into a list 2. it then counts the type of files 3. finally it prints out a report of the file types and each type count """ import glob import os def fileTypeCounter(path="."): counts = {} files = glob.glob(os.path.j...
''' Created on Jan 19, 2014 @author: rduvalwa2 ''' class mapEx: def init(self, mapp={'A':1, 'B':2}): self.inA = {} def upDate(self, key, value): self.inA.update({key:value}) def removeKey(self, key): del self.inA[key] def printInit(self): for...
""" Test list-of-list array implementations using tuple subscripting. """ import unittest import arr_dict3D class TestArray(unittest.TestCase): def test_zeroes(self): for N in range(4): a = arr_dict3D.array(N, N, N) for i in range(N): for j in range(N): ...
''' Created on May 25, 2014 @author: rduvalwa2 ''' from timeit import timeit from pprint import pprint """Callable Example Function and Method Callls The __call__() method is interestingβ€”its name implies that it has something to do with function calling, and this is correct. The interpreter calls any ca...
#!/usr/local/bin/python3 """secret_code.py this code uses simple encoding, adding 1 to the original ordinal values of the input letter for the output and making that the output value. The output string is then reversed """ debug = False user_input = input('Enter text: ') user_output = [] r_out = [] for letter i...
''' Cres1ted on s1pr 16, 2014 @s1uthor: rduvs1lws12 http://sts1ckoverflow.com/questions/2267466/overlos1ding-s1ugmented-s1rithmetic-s1ssignments-in-python http://www.decs1ls1ge.info/en/python/print_list http://sts1ckoverflow.com/questions/6771428/most-efficient-ws1y-to-reverse-s1-numpy-s1rrs1y http://sts1ckoverflow.co...
"""Compare my title function to str.title()""" import unittest def title(s): "How closes is this function to str.title()""" the_return = [] for word in s.split(): new_word = '' for ch in word: if ch[0]: new_word + ch.upper() else: new_...
#snake water and gun project -1 import random def gamewin(comp, user): if comp == user: return None elif comp == 's': #WHEN COMPUTER CHOOSES if user == 'g': return True elif user == 'w': return False elif comp == ' w': #WHEN COMPUTER ...
# Hanna Magan # Course: CS151-02, Dr. Rajeev # Date: 10/4/21 # Programming Assignment: 2 # Program Inputs: Month (1-12) and year # Program Outputs: Number of days in the month month = input("Input month (1-12):") year = input("Input year") leapYear = False #Program calculates if the year is a leap year. if year % 4 =...
from macros import BOARDW from macros import BOARDH # FUNCTIONS def drawBoard(board): for row in board: print("\n" + '-' * 13 + "\n| ", end = "") for char in row: print(char + " | ", end = "") print("\n" + '-' * 13, end = '\n\n') def gameover(): return 0 def checkGameover():...
# Importing the required Modules import os import csv import sys # Assuming CSV file and main.py files will be stored in the same directory # Defining the file object # os.path.join(sys.path[0] pointing to the same path as the main.py exists in budget_data_csv = os.path.join(sys.path[0], 'budget_data.csv') # Declarin...
from tkinter import* from tkinter.messagebox import* import math as m # creating a window window=Tk() window.title('My Calculator') window.geometry('380x400') #text label headinglabel=Label(window , text='CALCULATOR' , font=('Courier New ' , 25 , 'bold')) headinglabel.pack(side=TOP) #Text field textfie...
#Q.1- Write a program to create a tuple with different data types and do the following operations. #1. Find the length of tuples keyword=(2,5,3,'Aman','Deep') print(len(keyword)) #Q.2-Find largest and smallest elements of a tuples. numbers=(3,4,6,2,43,) print(max(numbers)) print(min(numbers)) #Q.3- Write a program t...
#:: Insertion sort with a complexity of O(n2) #:: basically you are partioning the array into a sorted and unsorted part def insertionSort(array): for i in range(1, len(array)): value = array[i] hole = i while hole > 0 and array[hole-1] > value: array[hole] = array[hole-1] ...
import random """This program plays a game of Rock, Paper, Scissors between two Players, and reports both Player's scores each round.""" moves = ['rock', 'paper', 'scissors'] class Player: def move(self): return 'rock' def learn(self, my_move, their_move): self.their_move = their_move ...
#!/usr/bin/python3 ################################################################ #Let the user know what the program does and what info it needs# ################################################################ print("Welcome to Mr. BMI") ######################################################################### #...
#This program downloads the data from the last 2 years of 13F-HR filings from a pre-selected group of hedge funds. #Each funds filings will be saved in a .json file contained in a folder called 'filings' in the working directory. import auto_run as ar import demo_run as dr def run_auto_or_demo(): print("Type demo ...
__author__ = 'alex.facanha18@gmail.com <asfmegas.github.io>' import sys try: import sqlite3 sqlite3.version except Exception as erro: print('Problema com o sqlite3. Verifique se ele estΓ‘ instalado.') sys.exit() class Database(object): def __init__(self): self.db = None self.cursor = None self.__conection()...
z=input("Enter your mRNA: ") b=input("Enter your DNA: ") print("/////////////////////////////////////////////////////////////////////////") #counts all the ATCG's of mRNA Z=z .count("G") c=z .count("C") P=z .count("A") O=z .count("T") #counts all the ATCG's of DNA B=b .count("G") D=b .count("C") K=b .count("A") M=b .c...
print("Give me an amount of money in whole ponds and I will tell you how many notes and/or coins it would convert to:") cash = int(input("Enter an amount of money in whole ponuds: Β£")) twenty = cash // 20 remainder = cash % 20 ten = remainder // 10 remainder = remainder % 10 five = remainder // 5 remaind...
#Paul Njenje #15/09/2014 #Class_exercise Revision #1 #ask for 4 numbers number1 = int(input("Enter a number: ")) number2 = int(input("Enter another number: ")) number3 = int(input("Enter another one: ")) number4 = int(input("Enter one last number: ")) #create a variable that is the sum of the 4 numbers ...
import csv from datetime import datetime, timedelta def get_data(date_start, date_end): """ Get meter usage data for between the start and end date """ # csv filename filename = "meterusage.csv" # user specified start date start = datetime.strptime(date_start, '%Y-%m-%d') # user specifi...