text
stringlengths
37
1.41M
""" Given a rectangle with sides parallel to X and Y axis and N points in X-Y co-ordinates, print the total number of points that lie strictly inside the rectangle. Input The first line consist of a single integer T - the number of test cases. For every test case the input is as follows - First Line consists of x1 y1...
""" Midori like chocolates and he loves to try different ones. There are N shops in a market labelled from 1 to N and each shop offers a different variety of chocolate. Midori starts from ith shop and goes ahead to each and every shop. But as there are too many shops Midori would like to know how many more shops he ...
""" Problem Link: https://practice.geeksforgeeks.org/problems/compete-the-skills/0 A and B are good friend and programmers. They are always in a healthy competition with each other. They decide to judge the best among them by competing. They do so by comparing their three skills as per their values. Please help them ...
""" Problem Link: https://practice.geeksforgeeks.org/problems/display-longest-name/0 Given a list of names, display the longest name. Input: First line of input contains an integer T, the number of test cases. For each test case, there will be two lines. First line contains integer N i.e. total number of names, and...
""" Given a string consisting of alphabets and others characters, the task is to remove all the characters other than alphabets and print the string so formed. Input: The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains a string S. Output...
""" Find the smallest number that can be framed using the series created by the digits obtained by raising the given number ( "a" ) to the power from 1 to n i.e. a^1 , a^2 , a^3 .......a^n . We get b1,b2 , b3 , ........... bn . Using all the digits ( including repeating ones ) that appear inb1 ,b2 , b3 .... b...
""" There will be ‘t’ test cases having an integer. You have to sum up all the digits of this integer. For e.g. For 6754, the answer will be 6 + 7 + 5 + 4 = 22. Input Format: First line will have an integer ‘t’ denoting the number of test cases. Next ‘t’ lines will have an integer ‘val’ each. Output format: Print ‘t...
""" Problem Link: https://practice.geeksforgeeks.org/problems/small-factorial/0 Calculate factorial of a given number N. Input: The first line contains an integer 'T' denoting the total number of test cases. In each test cases, it contains an integer 'N'. Output: In each seperate line output the answer to the proble...
""" Problem Link: https://practice.geeksforgeeks.org/problems/third-largest-element/1 Given an array of distinct elements, Your task is to find the third largest element in it. You have to complete the function thirdLargest which takes two argument . The first argument is the array a[] and the second argument is the ...
""" Problem Link: https://www.interviewbit.com/problems/max-min-05542f2f-69aa-4253-9cc7-84eb7bf739c4/ Problem Description Given an array A of size N. You need to find the sum of Maximum and Minimum element in the given array. NOTE: You should make minimum number of comparisons. Problem Constraints 1 <= N <= 105 -109 ...
""" Problem Link: https://practice.geeksforgeeks.org/problems/reverse-a-linked-list/1 Given a linked list of length N. The task is to reverse the list. Input: First line of input contains number of testcases T. For each testcase, first line contains length of linked list and next line contains the elements of linked...
""" Problem Link: https://practice.geeksforgeeks.org/problems/facing-the-sun/0 Monu lives in a society which is having high rise buildings. This is the time of sunrise and monu wants see the buildings receiving the sunlight. Help him in counting the number of buildings recieving the sunlight. Given an array H represe...
""" Problem Link: https://practice.geeksforgeeks.org/problems/find-minimum-and-maximum-element-in-an-array/0 Given an array A of size N of integers. Your task is to find the minimum and maximum elements in the array. Input: The first line of input contains an integer T denoting the number of test cases. T testcases f...
""" Problem Link: https://practice.geeksforgeeks.org/problems/set-bits/0 Given a positive integer N, print count of set bits in it. For example, if the given number is 6(binary: 110), output should be 2 as there are two set bits in it. Input: The first line of input contains an integer T denoting the number of test ...
""" Problem Link: https://practice.geeksforgeeks.org/problems/average/0 Given a stream of numbers, print average or mean of the stream at every point. Input: The first line of input contains an integer T denoting the number of test cases. For each test case there will be two lines. The first line contains an integer ...
""" Problem Link: https://practice.geeksforgeeks.org/problems/add-two-numbers-represented-by-linked-lists/1 Given two numbers represented by two linked lists of size N and M. The task is to return a sum list. The sum list which is a linked list representation of addition of two input numbers. Input: First line of in...
""" Problem Link: https://practice.geeksforgeeks.org/problems/remove-duplicate-elements-from-sorted-array/1 Given a sorted array A of size N. The function remove_duplicate takes two arguments . The first argument is the sorted array A[ ] and the second argument is 'N' the size of the array and returns the size of the...
""" Problem Link: https://practice.geeksforgeeks.org/problems/finger-game/0 Count the given numbers on your fingers and find the correct finger on which the number ends. The first number starts from the thumb, second on the index finger, third on the middle finger, fourth on the ring finger and fifth on the little f...
""" Problem Link: https://practice.geeksforgeeks.org/problems/twice-counter/0 Given an array of n words. Some words are repeated twice, we need count such words. Input: The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains an integer n deno...
""" Problem Link: https://practice.geeksforgeeks.org/problems/path-in-matrix3805/1 Given a NxN matrix of positive integers. There are only three possible moves from a cell Matrix[r][c]. Matrix [r+1] [c] Matrix [r+1] [c-1] Matrix [r+1] [c+1] Starting from any column in row 0, return the largest sum of any of the paths ...
""" You are given a number N. Determine the number of positive even integers that are smaller than or equal to it and are not a multiple of 4. Input Format The first line contains a single integer T, denoting the number of test cases. Each of the next T lines contains a single integer, denoting the value of N. Output...
""" Problem Link: https://practice.geeksforgeeks.org/problems/chocolate-distribution-problem3825/1 Given an array A[ ] of positive integers of size N, where each value represents the number of chocolates in a packet. Each packet can have a variable number of chocolates. There are M students, the task is to distribute...
""" Given an array of penalties, an array of car numbers and also the date. The task is to find the total fine which will be collected on the given date. Fine is collected from odd-numbered cars on even dates and vice versa. Input: The first line of input contains an integer T denoting the number of test cases. The...
""" Problem Link: https://practice.geeksforgeeks.org/problems/identical-linked-lists/1 Given a Singly Linked List of size N. The task is to complete the function areIdentical(), which checks whether two linked list are identical or not. Two Linked Lists are identical when they have same data and arrangement of data i...
""" Problem Link: https://practice.geeksforgeeks.org/problems/binary-array-sorting/0 Given a binary array, sort it in non-decreasing order Input: First line contains an integer denoting the test cases 'T'. Every test case contains two lines, first line is size and second line is space separated elements of arra Ou...
""" Problem Link: https://practice.geeksforgeeks.org/problems/delete-without-head-pointer/1 You are given a pointer/reference to a node to be deleted in a linked list of size N. The task is to delete the node. Pointer/reference to head node is not given. You may assume that the node to be deleted is not the last no...
""" Given a number your task is to complete the function convertFive which replace all zeros in the number with 5 and returns the number. Input: The first line of input contains an integer T denoting the number of test cases . Then T test cases follow . Each test case contains a single integer N denoting the number. ...
""" Given an array, we need to find that element whose value is equal to that of its index value. Input: The first line of input contains an integer T denoting the number of test cases. The first line of each test case is N,N is the size of array. The second line of each test case contains N input A[]. Output: Print...
""" Problem Link:https://www.hackerearth.com/problem/golf/is-it-the-same-1/ You are given two strings. You have to check if the strings are permutations of each other and output "YES" or "NO" accordingly without quotes. Input: 2 lines of input each containing a string. (a to z and 0 to 9) Output: A single line c...
""" Given a number N, you need to find if its digital root is prime or not. DigitalRoot of a number is the repetitive sum of its digits until we get a single digit number. Eg.DigitalRoot(191)=1+9+1=>11=>1+1=>2 Input: The first line of the input contains a single integer T, denoting the number of test cases. Then T t...
""" Problem Link: https://practice.geeksforgeeks.org/problems/find-length-of-loop/1 Given a linked list of size N. The task is to complete the function countNodesinLoop() that checks whether a given Linked List contains loop or not and if loop is present then return the count of nodes in loop or else return 0. Input...
""" Problem Link: https://practice.geeksforgeeks.org/problems/anshumans-favourite-number/0 You are given an integer input N and you have to find whether it is Anshuman’s favourite or not. If it is then print “YES” else print “NO”. A number is Anshuman’s favourite if it is either the sum or the difference of the inte...
#!/usr/bin/env python3 class Block: """1 sodoku block""" def __init__(self): self.squares = [None for i in range(9)] def setSquare(self, index, number): self.squares[index] = number def getSquare(self, index): return self.squares[index] def setSquareRowColumn(self, row, ...
# 在假设已经给定汇率的情况下,要能对两种不同的币种金额相加,并将结果转换为某一种币种; # 要将某一金额与某一个数相乘,并得到一个总金额 from stock.dollar import Dollar from stock.swiss_franc import SwissFranc from stock.money import Money def test_multi_stock_price(): five = Dollar(5) ten = five.times(2) assert ten.amount == 10 fifteen = five.times(3) assert fif...
""" 无重复字符的最长字串 使用滑动窗口的方法 滑动窗口都终点向字符串末尾移动,如果出现重复字符,则滑动窗口都起始位置一只向后移动,直到窗口内没有重复字符,再将终点向后移动 统计移动过程中出现的最长字符串 """ class Solution: def lengthOfLongestSubstring(self, s: str) -> int: from collections import defaultdict lookup = defaultdict(int) start = 0 end = 0 counter = 0 ...
#A brute solution class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ index_of_zero = 0 for i in range(len(nums)): if nums[i] == 0: nums.insert...
# -*- coding: utf-8 -*- """ Created on Tue Oct 23 15:42:20 2018 @author: zhaoxu 326. Power of Three """ class Solution(object): def isPowerOfThree(self, n): """ :type n: int :rtype: bool """ if n == 0: return False if n == 1: return...
# -*- coding: utf-8 -*- """ Created on Wed Mar 6 13:52:07 2019 @author: Sue 279. Perfect Squares """ import math class Solution(object): def numSquares(self, n): """ :type n: int :rtype: int """ if (n <= 0): return 0 if (n == 2): re...
# -*- coding: utf-8 -*- """ Created on Wed Aug 1 15:05:16 2018 @author: zhaoxu 169. Majority Element """ class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ return sorted(nums)[int(len(nums)/2)] ...
# -*- coding: utf-8 -*- """ Created on Thu Jan 17 14:42:41 2019 @author: Sue 814. Binary Tree Pruning """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def ha...
# -*- coding: utf-8 -*- """ Created on Mon Apr 8 14:59:03 2019 @author: Sue 103. Binary Tree Zigzag Level Order Traversal """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None from queue import Queue class ...
# -*- coding: utf-8 -*- """ Created on Wed Oct 24 11:14:13 2018 @author: zhaoxu 387 First Unique Character in s String """ class Solution(object): def firstUniqChar(self, s): """ :type s: str :rtype: int """ #this is accepted, which means functin 'in' is faster th...
# -*- coding: utf-8 -*- """ Created on Wed Feb 27 11:22:00 2019 @author: Sue 092. Reverse Linked List II """ # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def reverseToN(self, head, n): """ ...
# -*- coding: utf-8 -*- """ Created on Mon Oct 22 10:27:43 2018 @author: zhaoxu 121 Best Time to Buy and Sell Stock """ class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ #use two pointers #minPrice : is the l...
# # Testing.py # import unittest class TestCase(unittest.TestCase): def assertEqual(self, actual, expected): if actual == expected: return print "actual =", actual print "expected =", expected unittest.TestCase.assertEqual(actual, expected)
def binarySearch(alist, item): """Perform binary search for a data sequence. Binary Search starts off with comparing the item in the middle with the target. If the searched item is bigger than the target item, the second half of the sequence will be discarded. If the searched item is sm...
import datetime currentTime = datetime.datetime.now() hour = currentTime.hour minute = currentTime.minute def createSchedule(): schedule = [['Python video', 20], ['Python Project', 30], ['kleine pauze', 10], ['zang oefenen', 20], ['piano oefenen', 30], ['grote pauze', 30], ['proje...
# -*- coding: utf-8 -*- """ Created on Sat Sep 15 02:26:52 2018 @author: Anjani K Shiwakoti """ # METHOD 1: USING ITERATION def gcdIter(a, b): ''' a, b: positive integers returns: a positive integer, the greatest common divisor of a & b. ''' if a>b: bigger = a smaller = b ...
# -*- coding: utf-8 -*- """ Created on Sun Mar 31 13:47:46 2019 @author: Anjani K Shiwakoti Synopsis: Given starting address and destination address, calculate the geodesic distance between the two locations. A geodesic line is the shortest path between two points on a curved surface, like the Earth. ...
# -*- coding: utf-8 -*- """ Created on Sat Jan 2 14:19:59 2020 @author: Anjani K Shiwakoti Title: Solving Maximum Subarray Problem using Kadane's Algorithm (Dynamic Programming) Problem Definition: Given a 1-dimensional array (or a collection) find the contiguous subarray having the maximum sum of...
list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Print item in index 4 using bracket notation print(list[4]) # Print item in index 5 using negative [-1] index print(list[-4]) # Print every second item from the list print(list[0::2]) # Print items from 3rd to 5th print(list[3:5]) given_data = { 'foo': {'name': 'Foo', 'lastname...
def selection_sort(l): for i in range(len(l)): mi=i for j in range(i+1,len(l)): if(l[mi]>l[j]): mi=j l[i],l[mi]=l[mi],l[i] return l l=list(map(int,input().split())) print(selection_sort(l))
import numpy as np class game(): def __init__(self): self.board = [['']*3 for _ in range(3)] self.occupied_error = 'Place is Already occupied, choose another place' self.wrong_place_error = 'Place is not on the board, choose numbers from 0 to 2' self.winner = None def reset(sel...
''' current_number =1 while current_number <=5: print(current_number) current_number +=1 prompt = "\nTell me sonmthing, and I will repeat it back to you:" prompt +="\nEnteer 'quit to end the program:" message ="" while message !='quit': message = input(prompt) if message != 'quit': print(messa...
''' #字典列表 alien_0 = {'color':'green','points':5} alien_1 = {'color':'yellow','points':10} alien_2 = {'color':'red','points':15} aliens= [alien_0, alien_1, alien_2] for alien in aliens: print(alien) #创建一个用于储存外星人的空列表 aliens = [] #创建30个绿色的外星人 for alien_number in range(30): new_alien = {'color':'green','points':...
'''name = '' while name != 'your name': print('pleas type your name.') name = input() print('Thanke you !') #break 语句 while True: print('pleas type your name.') name = input() if name == 'your name ': break print('Thank you !') #continue 语句 while True: print('who are you?') name =...
class User(): def __init__(self,first_name,last_name): self.first_name=first_name self.last_name=last_name self.login_attempts=0 def describe_user(self): print(self.first_name.title()+self.last_name.title()) def greet_user(self): print("Hello,"+self.first_name.title(...
""" You toss n coins, each showing heads with probability p, independently of the other tosses. Each coin that shows tails is tossed again (once more, or when t=2). Let X be the total number of tails What is the probability mass function of the total number of tails? Start at main() function. """ import matplotlib.pa...
n1 = int(input('Um Valor:')) n2 = int(input('Outro valor:')) s = n1 + n2 m = n1 * n2 d = n1 / n2 di = n1 // n2 e = n1 ** n2 print('A soma eh {}, A muntiplicacao eh {} e a divisao e {:.3f}'.format(s , m, d), end='') #\n que a linha e end='' manter na mesma linha print('Divisao Inteira {} e Potencia{}'.format(di, e))
n = int(input("Digite um número de 4 a 9: ")) n_fora = n < 4 or n > 9 l = [] ana = 0 org = 0 while n_fora: n = int(input('Numero fora do intervalo! Digite novamente: ')) n_fora = n < 4 or n > 9 #print('Numero Aceito!!!') # essa mensagem pode ser trocado pelo inicio em outro código for x in range(1, n+1): n...
real =float(input('Quanto dinheiro voce tem na carteira? R$')) dollar = real / 3.27 euro = real / 4.85 yene = real / 0.65 peco = real / 0.31 print('Com R${:.2f} voce pode compra:\n US${:.2f}\n Er${:.2f}\n Ye${:.2f}\n Pc${:.2f}'.format(real, dollar, euro, yene, peco))
'''TUPLAS(que são listas imutaveis)- maneira de usar''' lanche = ('Hambúrger', 'Suco', 'Pizza', 'Pudim', 'Batata Frita') for comida in lanche: print(f'Eu vou comer {comida}') print() for cont in range(0, len(lanche)): print(lanche[cont]) print() for comida in enumerate(lanche): print(f'Eu vou comer {com...
num = input() c = 0 lista = [] temp = num.split() for x in temp: lista.insert(c, int((temp[c]))) c += 1 n = 0 while n != 'final': n = input() comando = n.split() if 'inserir' in comando[0]: lista.append(int(comando[1])) lista.sort() if 'remover' in comando[0]: lista.rem...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: Louan Mastrogiovanni """ import unittest from main import TestDbError, ConnectionDatabaseError from main import connect_to_db from main import get_users_list_from_db from main import add class TestCase(unittest.TestCase): """ Test class that check...
import math from queue import Queue import utils class Merger: """ A class for the merge functionality of posting files """ def __init__(self, path_to_files, file_type, docs_file, corpus_size=0): self.corpus_size = corpus_size self.queue = Queue() self.dict1 = None sel...
class Sudoku(): def __init__(self, g): self.grid = [[int(g[i*9+j]) for j in range(9)] for i in range(9)] def getGrid(self): return self.grid def displayCase(self, i, j): if self.grid[i][j] == 0: return "." return self.grid[i][j] def displayGrid(self): ...
mystr = "banana" myit = iter(mystr) ''' print(next(myit)) print(next(myit)) print(next(myit)) print(next(myit)) print(next(myit)) print(next(myit)) ''' for x in mystr: print(x)
a = 200 b = 33 if b > a: print("A is greater that B") elif a == b: print("A is equal to B")
""" This file contains code to produce a graph of response functions for various threshold values """ from matplotlib import pyplot as plt import math thresholds=[.95,math.sqrt(2)/2,.5] resolution=200 def autocratic(threshold,move): if move>threshold: return math.sqrt(1-threshold**2) x=threshold*mat...
""" This file contains a script to make a diagram showing how autocratic functions work """ from matplotlib import pyplot as plt from mkrespfuncgraph import autocratic import math resolution=101 plt.figure(figsize=(6, 6)) plt.hold=True plt.xlim(-2, 2) plt.ylim(-2, 2) plt.xlabel("Amount given to autocratic player")...
def Input(): num1=int(input('enter the first number')) num2=int(input('enter the second number')) return num1,num2 def addition(): num1,num2=Input() Result=num1+num2 return Result def output(): result=addition() print(result) output()
# create a BMI cal using OOP class BMI: # below expects weight and height def __init__(self, weight, height): self.weight = weight self.height = height self.pi = 3.14 # constant # above we define attr/var def get_bmi(self): answer = self.weight/(self.height ** 2)...
# If Else Statements #Boolean Expression print(20 > 10) print(20 == 10) print(20 < 10) print(bool("Hello World")) print(bool(20)) Python Conditions Equals -> x == y Not Equals -> x != y Less than -> x < y Less than or equal to -> X <= y Greater than -> x > y Greater than or equal to-> x >= y x = 70...
from random import randint import time import datetime def loading_files(): database = open('countries_and_capitals.txt') # loading capitals database databaseContent = database.read() database.close() listOfFileLines = databaseContent.splitlines() asciiFile = open('ascii1.txt') # loading asci...
arr = [int(i) for i in input().split()] for i in range(0,len(arr)): for j in range(i+1,len(arr)): if arr[j] < arr[i]: temp = arr[j] arr[j] = arr[i] arr[i] = temp print(arr)
str1 = "Apple" countDict = dict() for char in str1: count = str1.count(char) countDict[char]=count print(countDict)
def gcd(a, b): if(b == 0): return a else: rem = a%b return(gcd(b,rem)) a, b = map(int, input().split()) print(gcd(a, b))
from __future__ import print_function import numpy as np import chainer # Load the MNIST dataset from pre-inn chainer method train, test = chainer.datasets.get_mnist() # train[i] represents i-th data, there are 60000 training data # test data structure is same, but total 10000 test data print('len(train), type ', l...
from room import Room from character import Enemy from character import Character kitchen = Room('Kitchen') kitchen.set_description("A dank and dirty room buzzing with flies.") dining_hall = Room('Dining Hall') dining_hall.set_description('A large room with ornate golden decorations on each wall.') ballroom = Room('...
def create_record(name, telephone, address): """Create Record""" record = { 'name': name, 'phone': telephone, 'address': address, } return record def give_award(medal, *persons): """Give Medals to Persons""" for person in persons: print(person.title() + ' reciv...
cars = ['BMW', 'Mersedes', 'Audi', 'Lamborgini', 'Tesla'] print('\t*** Example 1 ***') my_str = '' for car in cars: my_str += car + ' ' print(my_str) print('\n\t*** Example 2 ***') number_list = list(range(0, 10)) for x in number_list: number_list[x] = x * 2 print(number_list) number_list.sort(reverse=True) p...
x = int(input ("year of birth")) years = 2019 - x if years <= 18: print("you are a minor") elif years <= 35: print("you are a god damn youth") else: print ("you are an elder")
def check_index(index): if index == -1: raise TypeError('Invalid input line.') def get_next_pair(s,start): # This function will extract next pair of <<XXXX>>OOOOO from the input string # s with a starting index = start. The return value is a tuple (entry,value,index) # The 3rd value is...
"""A3. Tester for the function common_words in tweets. """ import unittest import tweets class TestCommonWords(unittest.TestCase): """Tester for the function common_words in tweets. """ def test_empty(self): """Empty dictionary.""" arg1 = {} arg2 = 1 exp_arg1 = {} ...
class Solution: def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ for i in range(len(nums)): tmp = nums[i] for j in range(i, -1, -1): if 0 == j or nums[...
class Error(Exception): '''used for exception''' pass class ValueSmallError(Error): '''used for small value exception''' class ValueLargeError(Error): ''' used for large value error ''' number =20 while True: try: in_num = int(input("enter a number ")) if in_num > number: ...
#!/usr/bin/env python import string import inspect class ActStatus(object): """ An enumerator representing the status of an act """ SUCCESS = 0 FAIL = 1 RUN = 2 class Act(object): """ An act is a node in a behavior tree that uses coroutines in its tick function """ def __init__(self, childr...
# -*- coding: utf-8 -*- """ Created on Sat Dec 1 14:10:14 2018 @author: asingh368 """ from twilio.rest import Client # Your Account SID and Auth token from twilio account_sid = "" #Add account SID token here auth_token = "" #Add authorization token here # Both the above account SID and Auth token ...
A, B = map(int, input().split()) if(A%3==0): print("Possible") elif(B%3==0): print("Possible") elif((A+B)%3==0): print("Possible") else: print("Impossible")
import numpy as np import mnist import matplotlib.pyplot as plt from keras.models import Sequential from keras.layers import Dense from keras.utils import to_categorical from keras.layers import Dropout ## IMPORT IMAGES AND LABELS ################################################## train_images = mnist.train...
#this program let player put in a number and let comput guess #Computer need guess it smartly import random print(""" Welcome to upgraded version of guess my number! In this game player will input a secret number btw 1 and 100. Computer will try to guess it in as few attempts as possible """) secret=int(input("\nEnte...
import shelve def user(): name=input("Put in your name: ") try: score=int(input("Put in your score: ")) except: print("Sorry, you did not put in a whole number. Pls put in a whole number.") else: return name, score def update(name, score): hs=shelve.open("HSHS.dat") hs[n...
attributes={"strength":4, "health":5, "wisdom":8, "derpiness":15} money=30 items=[] print(""" Welcome to the Hero Creater Studios Please pick whether you want to buy(choice 0) or sell(choice 1) an attribute. The attributes are listed below strength-$4 ...
import csv import time def load_data(filename): """ """ data = [] with open(filename, newline='') as csvfile: reader = csv.DictReader(csvfile, delimiter=',') for row in reader: data.append(row) n_items = len(data) print(f"{filename} loaded into data ({n_items} item...
from functools import reduce def is_armstrong_number(number): if number == 0: return True single_digits = map(int, str(number)) each_digit_to_the_power_number_len = map(lambda n: n ** str(number).__len__(), single_digits) sum_all = reduce(lambda a, b: a + b, each_digit_to_the_power_number_len,...
from typing import List class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: previousNumsWithIndexes = dict() for index, num in enumerate(nums): indexOfPair = previousNumsWithIndexes.get(target - num) if(indexOfPair != None): return [...
from typing import List class Solution: def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]: result = [] for word in words: if self.is_matched_one_to_one(pattern, word): result.append(word) return result def is_matched_one_to_one(se...
import smbus import time import RPi.GPIO as GPIO # Setting the bus to its appropriate RPi version, this version being 3.7.6 bus = smbus.SMBus(1) # Setting GPIO pinmode as BCM (the numbers after the pin numbers) GPIO.setmode(GPIO.BCM) # Setting the address used for Arduino communication address = 0x04 ...
"""Module of encoder. StringToIntegerEncoder encode string into integer. ListToIntegerEncoder encode list into integer. See test section for code example. """ import json class StringToIntegerEncoder: """Encode string into integer. """ def __init__(self): """Use dict object to hash string. ...
""" Ejercicio 10 Escribir un programa que permita gestionar la base de datos de clientes de una empresa. Los clientes se guardarán en un diccionario en el que la clave de cada cliente será su NIF, y el valor será otro diccionario con los datos del cliente nombre dirección teléfono correo preferente donde pref...