text
stringlengths
37
1.41M
#!C:\Python34 # Bubble sort def sorted(x): for i in range(len(x)-1): for j in range (i+1, len(x)): print (x[i] , x[j]) if (x[i] > x[j]): temp = x[i] x[i] = x[j] x[j] = temp def main(): x= eval(input("enter list")) sorted(x) print (x) if __name__=="__main__": main()
#!C:\Python34 def dictionary_of_char(sentence, cwd= "str"): if (cwd= "paragra result ={} for ch in sentence: if result.get(ch) != None: result[ch] +=1 else: result[ch] =1 return result def main(): sentence = input("Enter your sentence") result = dictionary_of_char(sentence) print(result) #for ch ...
def highestSum(arr, k): highest_sum = float('-inf') n = len(arr) # n must not be smaller than k if n < k: return -1 # subarray starts at i for i in range(n - k + 1): # calculate sum of the subarray current_sum = 0 for j in range(k): print("Value fo i...
def add(a,b,c=0,d=0,e=0): return a+b+c+d+e print(add(10,20)) print(add(10,20,30)) print(add(10,20,30,40)) print(add(10,20,30,40,50))
#!C:\Python34 class stack: def __init__(self, size): print ("Stack constractured of size", size) self.stack = [] self.__size =size #print self.stack def push(self,data): status ="Failed" if not self.isFull(): self.stack.append(data) print (data, "Pushed to stack") status = "Passsed" return s...
#!C:\Python34 a= int(input("Enter the first integer")) b= int(input("Enter the Second integer")) print (a + b) print (a - b) print (a * b ) print (a // b) print (a ** b)
#!C:\Python34 def reverselist(x): if len(x)== 0: return x # for list [] , for string "" reverselist (x[1:]) print (x[0],end=" ") #y= (x[0]) #return y # return x.appendx[0] def main(): x= eval(input("Enter elements of the list")) print ("Original List is", x) reverselist(x) if __name__=="__main__": ma...
#!C:\Python34 def balance_check(s): #print(s) if len(s) %2 != 0: return False opening = set('([{') matches = set([( '(', ')' ), ( '[' , ']' ), ( '{', '}')]) # List of tuples of all pairs # implementing list as stack . Usebuilt in funstions of list stack =[] for param in s: #scaning string from ...
def patt(n,c): i=str(c)+"\t" j="\t" for x in range(n,0,-1): print(str(j*(n-x))+str(i*x)) ''' for i in range(n,0,-1): for _ in range(n-i): print("\t",end="") for _ in range(i): print("*\t",end="") print() ''' def main(): x=eval(input("Enter number of rows")) y=input("Enter charater\t") ...
#!C:\Python34 def reversecontainer(x): if len(x)== 0: #print ("Inside string length zero") if type(x) == str: # print ("When type is string") return x return list() y=reversecontainer(x[1:]) if type(x) == str: #print ("Build recursion") return y+ x[0] y.append(x[0]) return y def main(): x= [...
def variableargs(a,b,c,*d,**e): print(a) print(b) print(c) print(d) print(e) if __name__=='__main__': a,b,c=eval(input("Enter three numbers")) d=input("Enter a number or string") e='"name":"siddharth"'#not working, it is creates dictionary inside a dictionary variableargs(a,b+1,c,a,d,b,d=c,n=e)# d=c is also ...
def highestSum(arr, k): highest_sum = float('-inf') n = len(arr) # n must not be smaller than k if n < k: return -1 # Compute sum of first window of size k window_sum = sum([arr[i] for i in range(k)]) # Compute sums of remaining windows by # removing first element of previous...
def digit(n): s=0 while(n!=0): s=s*10+n%10 n=int(n/10) return s def main(): n=eval(input("Enter Digit\t")) print(digit(n)) if __name__=='__main__': main()
#s: string , k is steps class solution: def sumofdigit(self, s:str, k:int)->int: num = "" for x in s: #print (ord("a")) num += str(ord(x) - ord("a") +1 ) for _ in range(k): s = 0 for x in num: s+=int(x) num =str(s) return int(num) s= solution() print(s.sumofdigit("leeth" ,1))
#!C:\Python34 import math def prime(no): mat.sqrt(no) def getPrimes(inputlist): for number in inputlist: if ISPrime(number): yield number def main(): x =GetPrimes(range(1,10)) print (type(x)) print (next(x))
#!C:\Python34 def patterndouble(n): for i in range (1, n+1): k = i for _ in range (1, i+2): print(k, end=' ') k *=2 print ( " " , end= "\n") def main(): no= eval(input ("enter the number")) print (patterndouble(no)) if __name__=="__main__": main() ''' Pattern output 1 2 2 4 8 3 6 12 24 4 ...
def third(x,y): z=[] i,j=0,0 while True: if i == len(x): z.extend(y[j:]) break elif j == len(y): z.extend(x[i:]) break elif x[i] < y[j]: z.append(x[i]) i+=1 elif x[i] > y[j]: z.append(y[j]) j+=1 return z def main(): print("Enter 1st list Elements") x=[int(a) for a in input().sp...
#!C:\Python34 st = str(input("Enter string : ")) print ("After replacing occurrences in string : ", st[0]+st[1:].replace(st[0],"*"))
#!C:\Python34 def pattern1(num): n = 0 for i in range(1, num +1): for _ in range(1, num-i+1 ): print (" ", end = "" ) # loop to print star while n != (2 * i - 1): print("*", end = "") n = n + 1 n=0 print ("" , end= "\n") n = 0 num= num-1 for i in range (1, num +1): for _ in ra...
import re import os def RemoveComments(x): #multiLine = re.compile("'''.*?'''") #singleLine = re.compile("#.*.") commentsRE = re.compile(r"(#.*.)|('''.*?''')") f=open(x,"r") Data = f.read() Data = re.sub(commentsRE,"",Data) f.close() x+='_comments_removed.txt' f=open(x,'w') f.write(Data) f.close() print("D...
#!C:\Python34 def divisibleby8(no): return (no & 7) == 0 def main(): no= eval(input ("enter the number")) print (divisibleby8(no)) if __name__=="__main__": main()
#!C:\Python34 import functools def Multiply(x,y): print (x,y) return x*y print(functools.reduce(Multiply, range(1,10)))
''' Given the head of a singly linked list, return true if it is a palindrome. Example 1: Input: head = [1,2,2,1] Output: true Example 2: Input: head = [1,2] Output: false ''' def isPalindrome(self, head: ListNode) -> bool: vals = [] current_node = head while current_node is not None: vals.appe...
"""Пользователь вводит целое положительное число. Найдите самую большую цифру в числе. Для решения используйте цикл while и арифметические операции.""" user_input = int(input("Введите целое положительное число: ")) a = user_input max_number = a%10 a = a//10 while a > 0: if a%10 > max_number: max_number = a...
import random import pyperclip symbol = 0 lower = 0 upper = 0 number = 0 count = 0 password = [] length = input("Hey, Welcome. Just say me how many characters do you want in your password? (default 128)\n") length = 128 if length == '' else int(length) while count < length: rand = random.randint(0, 3) if ran...
#!/usr/bin/env python import sys import csv # input comes from STDIN data = sys.stdin.readlines() # parse the input we got from csv reader = csv.reader(data) # remove header header = next(reader) if header != None: for line in reader: # write result to STDOUT print '%s\t%s' % (line[9].capitalize(), 1)
n=int(input("Enter a number:")) if n>0: print("The number is +ve") else: print("The number is -ve")
# coding= utf-8 class Foo(object): def __init__(self, name): self.name = name def __setattr__(self, key, value): print("call __setattr__") # self.key = value # 这一句会造成无穷递归,因为这一句等效:self.name = name # 正是self.name = name 触发了__setattr__(self,key,value)的执行 self.__dict__[key]...
# -*- coding: utf-8 -*- class Fib(object): def __init__(self): print('__init__') self.a, self.b = 0, 1 # 初始化两个计数器a,b def __iter__(self): print('exec __iter__') return self # 实例本身就是迭代对象,故返回自己 def __next__(self): print('exec next') self.a, self.b = self.b, s...
# -*- coding: utf-8 -*- import threading import time # mutexA = threading.Lock() # Lock是一个类 # mutexB = threading.Lock() recur_lock = threading.RLock() class MyThread(threading.Thread): def __init__(self): # threading.Thread.__init__(self) super().__init__() # 这里不要self参数,只要除去self外的参数 def ...
# -*- coding: utf-8 -*- # 有两种情况: # 一种情况: =后面跟的另外一段内存地址的话,不会更改 # 另外一种情况:在原来内存地址直接修改append, 会更改 test_list = [1, 2, 3] # 全局空间的test_list def change(t): # t也是内置空间的名字t t.append(4) print "before change test_list= %s" % test_list # 全局空间的test_list change(test_list) # t = test_list, t和test_list都是对同一内存地址的引用 # t = [1...
# -*- coding: utf-8 -*- import datetime now = datetime.datetime.now() last = datetime.datetime(year=2016, month=9, day=3, hour=12) delta = now - last print(delta) # 366 days, 0:07:38.303065 # delta表示一段时间,有days,时,分,秒,微秒属性 # 也可以将其初始化 import datetime now = datetime.datetime.now() print(now) delta = datetime.timedelta(d...
# -*- coding: utf-8 -*- # 继承的好处: # 继承可以把父类的所有功能都直接拿过来,这样就不必重零做起, # 子类只需要新增自己特有的方法,也可以把父类不适合的方法覆盖重写; class Animal(object): def __init__(self, name, age): self.name = name self.age = age def walk(self): print('%s is walking' % self.name) def say(self): print('%s is saying'...
# -*- coding: utf-8 -*- test_list = [1,2,3] # 全局空间的test_list def change(): # 这样相当于在内部定义了名字(内置空间的test_list) test_list = [1,6] print "before change test_list= %s" % test_list #全局空间的test_list change() print "after change test_list= %s" % test_list #全局空间的test_list # before change test_list= [1, 2, 3] # after...
import time def A(): print("第一次由B调到A") while True: print('------A-----') time.sleep(0.1) yield print("由B返回A") def B(a): for i in range(3): print("此时B i = %d" % i) time.sleep(0.1) next(a) # 生成器一遇到next就会执行a函数的代码,A函数在yield处保存,从A函数并返回到此次 # 从A函数...
# -*- coding: utf-8 -*- #strftime是将struct time转化成字符串time(人能读时间) import time time_format = '%x' # 小写的x表示年月日date日期 local_tuple = time.localtime() print(time.strftime(time_format, local_tuple)) time_format = '%X' # 大写的X表示时分秒time local_tuple = time.localtime() print(time.strftime(time_format, local_tuple)) time_format...
#!/usr/bin/python # The Mayan Long Count[2] calendar is a counting of days with these units: "* # The Maya name for a day was k'in. Twenty of these k'ins are known as a winal # or uinal. Eighteen winals make one tun. Twenty tuns are known as a k'atun. # Twenty k'atuns make a b'ak'tun.*". Essentially, we have this p...
''' File: Assignment1_Task1.py Author: Steven Phung Class: CS 2520.01 - Python for Programmers Assignment: Assignment #1_Task #1 Purpose: Practicing if statements. BMI can be calculated using Imperial (American) or Metric (English) system. Note that we'd like the user to choose whether...
# leetcode 491 class Solution(object): def findSubsequences(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ res = [] def dfs(nums, start, tmp): # 使用dict去重,常规append + pop TLE。 dic = {} if len(tmp) > 1: ...
# leetcode 212 单词搜索 # 基本性质 # 1,根节点不包含字符,除根节点以外每个节点只包含一个字符。 # 2,从根节点到某一个节点,路径上经过的字符连接起来,为该节点对应的字符串。 # 3,每个节点的所有子节点包含的字符串不相同。 class Solution: def findWords(self, board, words): # build trie begin ### trie = {} for word in words: t = trie for w in word: #...
import sys import pygame import random from sprite import * from pygame.sprite import Group def date_read(): fd_1 = open("data.txt","r") best_score = fd_1.read() fd_1.close() return best_score def update_screen(screen,swk,arrows,energy): # swk.update() swk.blitme(screen,energy) for arrow ...
""" Base class for the different user model classes """ from .abs_user import AbsUser class BaseUser(AbsUser): def __init__(self, username="", password="", role=None): # todo: raise exception if username, password and role is not set at object creation self._username = username self._pass...
import numpy as np friend=["Kevin","Allen","Jim","Jim","Zelle",'Bill'] re =friend.pop() print(friend) print(re) lucky_number=[4,8,3,1,0] friend.extend(lucky_number) print(friend) #insert Kelly friend.insert(1,'Kelly') print("insert Kelly",friend) #remove Kelly friend.remove('Kelly') print("#remove Kelly",friend) #re...
# 使用format()函数进行格式化 # print("尊敬的 {0} 用户,您好! 您当月已用话费 {1} 元, 可用话费为 {2} 元,可用积分 {3} 分." format('颛孙鹏程',12.12,23.43,1234)) # 报错,format()是一个函数,需要调用的, 用 . 调用 # print("尊敬的 {0} 用户,您好! 您当月已用话费 {1} 元, 可用话费为 {2} 元,可用积分 {3} 分.".format('颛孙鹏程',12.12,23.43,1234)) # ---OK # 小明的成绩从去年的72分提升到了今年的85分,请计算小明成绩提升的百分点, # 并用字符串格式化显示出'xx.x%...
from collections import namedtuple,deque Point = namedtuple('Point',['x','y']) p = Point(1,2) print(p.x) q = deque(['a','b','c']) q.append('x') q.appendleft('y') print(q)
# 日志捕获 import logging def foo(s): return 10 / int(s) def bar(s): return foo(s) * 2 def main(): try: bar('0') except Exception as e: logging.exception(e) # print("哈哈哈") finally: print("我去你吗的") # main() # print('END') # 异常抛出 # 我把我的错误信息,返回到上层 def foo1(s): try...
# type()用于判断对象的类型 ''' class Student(object): pass student = Student() print(type(student)) print(type(123)) ''' # types用于判断方法的类型 ''' import types def fun1(): print("hello world") return if type(fun1) == types.FunctionType: print(True) ''' # isinstance() 就很高级了 ''' - 判断对象类型 - 判断方法类型 - 判断某一个变量是否属于某一类 print("1--...
from datetime import datetime,timedelta # 获取当前时间 print(datetime.now()) # 获取指定时间 print(datetime(2015,4,19,12,20)) # 获取时间戳 print(datetime(2015,4,19,12,20).timestamp()) # 时间戳转时间 t = datetime.now().timestamp() print(datetime.fromtimestamp(t)) # 时间戳转UTC时间 print(datetime.utcfromtimestamp(t)) # string转时间 print(datetime....
class Student(object): def getName(self): return self.name def setName(self,name): self.name = name return student = Student() student.setName("lisi") print(student.getName()) # @property 是把一个方法变成属性,可以直接通过属性直接调用 class Teacher(object): @property def name(self): return self._name @name.setter def name(se...
stanciya = { "A": '1 час.', "B": '2 часа.', "C": '3 часа.', "D": '4 часа.', "E": '5 часа.' } st = input("Введи станцию: ") st = st.upper() if st in stanciya: print(stanciya[st])
def gcd(x, y): a = x b = y if (b == 0): return a else: while b != 0: c = a % b print(f'{a} {b} {c}') a = b b = c return a print(gcd(1970, 1066))
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def createListNode(self, target: list, index = 0): if (index != len(target)): return ListNode(val=target[index], next=self.createListNode(target, index + 1)) def addTwoN...
# An Arithmetic Progression is defined as one in which there is a constant difference between the consecutive terms of a given series of numbers. You are provided with consecutive elements of an Arithmetic Progression. There is however one hitch: exactly one term from the original series is missing from the set of numb...
""" Define a function that takes in two numbers a and b and returns the last decimal digit of a^b. Note that a and b may be very large! For example, the last decimal digit of 9^7 is 9, since 9^7 = 4782969. The last decimal digit of (2^200)^(2^300), which has over 10^92 decimal digits, is 6. The inputs to your functio...
# -*- coding: utf-8 -*- """ Created on Sun Mar 17 10:46:21 2019 @author: 16327143仲逊 """ annual_salary=float(input('Enter your starting annual salary:' )) total_cost=1000000 portion_down_payment=0.25 need_pay=portion_down_payment*total_cost def calculate_36month_after(portion_saved,monthly_salary): "...
# Picodisplay demo Make Magazin 2021 (caw) import time, random # Boilerplate code which will be needed for any program using the Pimoroni Display Pack # Import the module containing the display code import picodisplay as display def makemagazin(): display.set_pen(makeRed) display.text("Make:", 10, 10, 64, 6) ...
"""Useful miscellaneous functions.""" from typing import Callable def get_linear_anneal_func( start_value: float, end_value: float, end_steps: int ) -> Callable: """Create a linear annealing function. Parameters ---------- start_value : float Initial value for linear annealing. end_va...
""" LeetCode Problem: 445. Add Two Numbers II Link: https://leetcode.com/problems/add-two-numbers-ii/ Language: Python Written by: Mostofa Adib Shakib Time Complexity: O(n) Space Complexity: O(n) """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # s...
def tripleTheChances(chances): quantidade = chances[0] chances = chances[1:] chances.sort() for i in range(quantidade): chances[i] = chances[i] * 3 return chances d = tripleTheChances([5, 2, 3, 5, 8, 10]) print(d)
def action(input_char, replace_with, move, new_state): global tapehead, state if tape[tapehead] == input_char: tape[tapehead] = replace_with state = new_state if move == 'L': tapehead -= 1 else: tapehead += 1 return True return False string = ...
""" An Elf just remembered one more important detail: the two adjacent matching digits are not part of a larger group of matching digits. Given this additional criterion, but still ignoring the range rule, the following are now true: 112233 meets these criteria because the digits never decrease and all repeated digit...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun Apr 9 16:39:26 2017 @author: neelabhpant """ from __future__ import division # want 3 / 2 == 1.5 import re, math, random # regexes, math functions, random numbers import matplotlib.pyplot as plt # pyplot from collections import defaultdict, Counter fr...
# Matrix Loop # Demonstrates the use of random and loops to create a matrix looking program import random for matrix in range(1000): print(random.randrange(2)) input("\n\nPress ENTER to exit out of the program.")
# Trust Fund Buddy - Bad # Demonstrates a Logical Error print( """ Trust Fund Buddy Totals your monthly spending so that your trust fund doesn't run out (and you're forced to get a real job). Please enter the requested, monthly costs. Since you're rich, ignore penni...
import random def insert(list, item): tempList = list indexList = [] for i in range(0, len(list)): indexList.append(i) while(len(tempList) > 1): middle = len(tempList) // 2 if(item < tempList[middle]): tempList = tempList[:middle] indexList = ...
# day2 assignment #delete an element from begining def delete_array_begining(arr): if len(arr)<1: print("array is empty cant delete") else: # for i in range(len(arr)): # del_element=arr1.array('i',arr) # del del_element[0] my_list=arr my_list.remove(arr[...
import time class Timer: def __init__(self): self.start_time = time.time() self.end_time = 0 self.steps = 0 def step(self): self.steps += 1 self.end_time = time.time() def get_speed(self): speed = 1.0 * self.steps / (self.end_time - self.start_time) ...
""" Percent Daily Return Exercise In this exercise, you are given the stock values for several consecutive days for acme corporation. Your job is to calculate the "percent daily return" for each day. The percent daily return is the percentage that the stock changes each compared to the day before. Below you are gi...
import numpy as np import scipy.io as sio import matplotlib.pyplot as plt from linearRegCostFunction import * from trainLearnReg import * from learningCurve import* from plotFeatures import* from featureNormalize import* from plotFit import* from validationCurve import * print('Loading and Visualizing Data .....
""" Uzrakstiet programmu Python, lai pārbaudītu, vai norādītā vērtība ir vērtību grupā. Testa dati: 3 -> [1, 5, 8, 3]: taisnība -1 -> [1, 5, 8, 3]: nepatiesa """ cipari = [1, 5, 8, 3] if 3 in cipari: print("taisnība") if -1 in cipari: print("nepatiesi")
""" glc.shapes.segment ================== (c) 2016 LeoV https://github.com/leovoel/ """ from math import atan2, hypot from .shape import Shape class Segment(Shape): """Draws a portion of a line. The drawn segment will animate from the start of the line to the end of it during the an...
""" glc.shapes.circle ================= (c) 2016 LeoV https://github.com/leovoel/ """ from .shape import Shape from ..utils import rad class Circle(Shape): """Draws a circle. This can also draw an arc, if you use the start and end angle properties to do so. Create it using: .. ...
import matplotlib.pyplot as plt import numpy as np def make_column_chart(): number_of_data_sets = int(input("Enter number of data sets: ")) averages = [] labels = [] title = str(input("Enter title: ")) x_label = str(input("Enter x axis title: ")) y_label = str(input("Enter y axis title: ")) ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: ahtouw """ __doc__ = """ Dependencies: pandas sklearn.preprocessing -> MinMaxScaler sklearn.decomposition -> PCA This module is for performing PCA on a dataset NOTE: DATA GETS SCALED DOWN PRIOR TO PCA This...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 6 10:57:22 2020 @author: staxx Brandon Jackson """ # Function we worked on that was not used def feature_extract(df): ''' Take in dataframe object and check for NaN values and handle ---------- df_train : dataframe t...
import numpy as np import matplotlib.pyplot as plt import pandas as pd dataset = pd.read_csv("/Users/nithinkyatham/Downloads/Mall_Customers.csv") X = dataset.iloc[:,[3,4]].values # Elbow method using WCSS from sklearn.cluster import KMeans # Creating a list to hold WCSS values for different K Values wcss = [] for ...
flag = list('flag{caesar_ciphers_are_basically_a_formality}') for m in range(len(flag)): cur = flag[m] if cur == 'z': flag[m] = 'a' elif cur == 'Z': flag[m] ='A' elif 65 <= ord(cur) <= 89 or 97 <= ord(cur) <= 121: flag[m] = chr(ord(cur) + 1) print ''.join(flag)
from Tkinter import * window = Tk() window.title("MGH App") lbl = Label(window, text="Gravitational Potential Energy Calculator") lbl.grid(column=0, row=0) window.geometry("600x600") mass_q = Label(window, text="What is the mass in kilograms?") mass_q.grid(column=0, row=1) Mass = Entry(window, width=5) Mass.grid(colum...
import collections Nucleotides = ["A","T","G","C"] def validateSeq(dna_seq): tmpseq = dna_seq.upper() for nuc in tmpseq: if nuc not in Nucleotides: return False return tmpseq def countNucFrequency(seq): tempFreqDict = {"A": 0, "T": 0, "G": 0, "C": 0} for nuc in seq: ...
def division(a, b): try: result = a / b except ZeroDivisionError as e: return "divide by zero, error: %s"%e except TypeError as e: return division(int(a), int(b)) else: return result finally: print ("good, well done!")
__author__ = 'Guruguha' # Percentages num_of_students = int(input()) if num_of_students < 2 or num_of_students > 10: print("Enter valid number of students") else: count = num_of_students student_data = [] valid_input = True while count != 0: values = input() input_list = values.spl...
#!/bin/python3 import sys n = int(input().strip()) fact = 1 itr = 1 while itr <= n: fact *= itr itr += 1 print(fact)
nums=int(input()) status=None for i in range(2,nums): if nums>1: if nums%i==0: status='Not Prime' break else: status='Prime' print(status)
# -*- coding:utf-8 -*- from binascii import * import sys #import passwordlist if len(sys.argv) != 3 or sys.argv[1] not in ('0','1'): sys.exit( '''Useage: python exchange.py <mode> <'exchange-string'> Examples: python exchange.py 0 'hello' python exchange.py 1 '12345' ''' ) def a2b(exc_num): src_pw = '' ...
""" This is your coding interview problem for today. This problem was asked by Microsoft. Suppose an arithmetic expression is given as a binary tree. Each leaf is an integer and each internal node is one of '+', '−', '∗', or '/'. Given the root to such a tree, write a function to evaluate it. For example, given the...
""" This problem was asked by Facebook. Given a function f, and N return a debounced f of N milliseconds. That is, as long as the debounced f continues to be invoked, f itself will not be called for N milliseconds. """ import time def debounce(f, N): """ Returns a debounced function s.t. f is executed af...
""" This is your coding interview problem for today. This problem was asked by Dropbox. What does the below code snippet print out? How can we fix the anonymous functions to behave as we'd expect? functions = [] for i in range(10): functions.append(lambda : i) for f in functions: print(f()) """ if __name__ ==...
""" This question was asked by Google. Given an integer n and a list of integers l, write a function that randomly generates a number from 0 to n-1 that isn't in l (uniform). Ex: n = 7 l = {0, 1, 4} the function should return any random number { 2, 3, 5, 6 } with equal probability. """ import numpy as np class Un...
""" Return a tuple representing the minumum index range of an array that is out of order. For example, the array [3, 7, 5, 6, 9] would return (1, 3). """ def min_arr_range(arr): """ Returns minimum index range that is out of order. Input: arr: numeric list Returns: (n, m) where n and m...
import random import math class Player: player_list = {} def __init__(self, name, money=1500): self.name = name self.money = money self.jail = False self.jail_counter = 0 self.position = 0 # Colours, Utilities, Railroads self.properties = [{}, [], []] ...
range(3) == [0, 1, 2] >>> for i in range(5): ... print(i) ... 0 1 2 3 4
""" Given an array A[ ], find maximum and minimum elements from the array. Input: The first line of input contains an integer T, denoting the number of testcases. The description of T testcases follows. The first line of each testcase contains a single integer N denoting the size of array. The second line contains N s...
""" Given a array of length N, at each step it is reduced by 1 element. In the first step the maximum element would be removed, while in the second step minimum element of the remaining array would be removed, in the third step again the maximum and so on. Continue this till the array contains only 1 element. And print...
""" Given an Array, Find the maximum sun sub-array I/P: a = [1, 2, 5, -7, 1, 2] O/P: [1, 2, 5] Explanation: sum of sub array [1, 2, 5] is 8 and it is maximum sum of all sub-array of given array. """ def get_max_sum_subarray(arr): maxi = 0 element_sum = 0 main_max = 0 temp = [] for i in arr: ...
""" 1. You are given an array A of size N. You need to print elements of A in alternate order. https://practice.geeksforgeeks.org/problems/print-alternate-elements-of-an-array/1 The first line of input contains T denoting the number of testcases. T testcases follow. Each test case contains two lines of input. The first...
import unittest # 1.1 - O(n) def all_unique(string): return len(set(string)) == len(string) # 1.2 O(n) def reverse_string(string): return string[::-1] # rev = "" # length = len(string) # for i in range(length)[::-1]: # rev += string[i] # return rev # 1.3 - should be O(n), two passes ...
from typing import Callable, Any counter_records = dict() def counter(func: Callable) -> Callable: def wrapped_func(*args, **kwargs) -> Any: func_to_call = func(*args, **kwargs) func_name = func.__name__ if func_name in counter_records: counter_records[func_name] += 1 ...
from itertools import combinations, chain def powerset(iterable): ''' Generate the powerset (set of all subsets) of a given iterable. ''' initialSet = list(iterable) return chain.from_iterable(combinations(intialSet, subSetSize) for subSetSize in range(len(intialSet) + 1)) def contains_edges(gra...
#Task 12 #Bond and Investment calculator #Programmer: Berto Swanepoel #This program will help anyone to calculate investment as well as calculate you monthly installment when wanting to buy a house. import math #This part is where you ask the user to make decision, I have also explained to the user what the me...
import random lista = ['PEDRA', "PAPEL", "TESOURA"] jogador = str(input("Escolha pedra, papel ou tesoura: ")).upper() computador = random.choice(lista) if jogador == "PEDRA" and computador == "TESOURA" or jogador == "TESOURA" and computador == "PAPEL" or jogador == "PAPEL" and computador == "PEDRA": print(f"O jogad...