text
stringlengths
37
1.41M
# -*- coding: utf-8 -*- # @Time : 2020/9/26 12:10 # @Author : yk # @FileName: SequenceSearch.py ''' 按照列表顺序去查找,找到则返回 ''' list = [5, 4, 6, 1, 2, 3, 2] def sequenceSearch(list, x, l): for i in range(l): if (list[i] == x): return i; return False; print(sequenceSearch(list, 2, len(list)))
s = 'My name is Python' #1 #print(len(s)) #2 counter = 0 for i in s: counter += 1 print(len(s)) #3
x=1 x2=10 while x<=x2: print(x, end=" ") x=x+1
s = 'my name is dhruvit' print("The original string is: ", s) new_str = "" for i in range(len(s)): if i != 0: new_str = new_str + s[i] print(new_str)
x=(int(input("Enter No.: "))) y=1 while y<=10: z=x*y print(x,"*", y, "=",z ) y=y+1
list = [] x = int(input("Enter No of elements: ")) print("Enter", x, "Numbers:") for i in range(x): y = int(input()) list.append(y) print(list) z = int(input("Enter the element which you want to delete: ")) list.remove(z) print(list)
import random import math from tkinter import * def read_cities(file_name): infile = open(file_name, "r") line = infile.readline() road_map = [] while line: value = tuple(line.rstrip('\n').split("\t")) value = (value[0], value[1], float(value[2]), float(value[3])) road_map.append(v...
def pairsum(arr, size, n): pair=set() for i in range(0, len(arr)): temp=n-arr[i] if (temp in pair): print(" Pair of given sum is", arr[i], "and", temp) pair.add(arr[i]) print("Enter elements in array in sorted order: ") arr=list(map(int, input().split())) print("Ente...
from tkinter import * def which_selected(): print("At {0}".format(select.curselection())) return int(select.curselection()[0]) def add_entry(): phonelist.append([fnamevar.get(), lnamevar.get(), phonevar.get()]) set_select() def update_entry(): phonelist[which_selected()] = [fna...
#age=int(input("How are you old ??\n")) #if(age>18): # print("\nGo get your beer!!\n") #else: # print("\nSorry !!! you're too small to drink beer\n") word = input("Enter word \n") if len(word) < 3 : print(word[:]) elif len(word) >= 3 : if word.endswith("ing"): print (word[:-3] + "ly") ...
def gcd(m,n): i=min(m,n) while(i>0): if (m % i == 0 & n % i == 0): return i else: i=i-1 print("GCD is : $$ ",gcd(18,3))
def gcd(m,n): cf=[] for i in range(1,min(m,n)+1): if(m%i==0 & n%i==0): cf.append(i) print("Common Factor Is : ",cf) return(cf[-1]) print("GCD is : ",gcd(79,5)) print("GCD is : ",gcd(18,12))
"""Numpy Encoder""" import json import numpy as np class NumpyEncoder(json.JSONEncoder): """Numpy Encoder Encode numpy object as JSON. """ def default(self, obj): """Override default encoder If the object is a 1D numpy array, encode it as JSON array. If the object is a nump...
def fib_recurs(x): if x == 0 or x == 1: return x return fib_recurs(x - 1) + fib_recurs(x - 2) print(fib_recurs(7))
class Stack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items) - 1] def size(self): return len(self.items) def is_matching_bracket...
"""Library for organizing track information into functional objects. """ class Track: def __init__(self, name, album, artists, popularity, track_id, album_id, duration_ms, explicit, release_date): self.name = name self.album = album self.artists = artists self.popularity = popularity...
from prat_03.minimax import calc_best_state_minimax from prat_03.state import State from prat_03.utils import create_initial_board from prat_03.utils import select_move_from_player def main(player_X, player_O): """ Main of the game. """ current_state = State(create_initial_board()) current_player =...
from utils.board_utils import * from copy import deepcopy def move_up(node, x, y): #Upwards movement if y != 0: for i in range(1, y + 1): if node.board[y - i][x] != BLANK_SPACE_CHAR: if i == 1: break coords = (x, y - i + 1) ...
import time import random from .node import * # values for the termination of the game BEST_VALUE_MINIMAX = 10000 # state value if the current player has won the game WORST_VALUE_MINIMAX = -10000 # state value if the opponent player has won the game def calculate_minimax(node, evaluator, first_turn, max_depth, playe...
from utils.board_utils import * def heuristic_function_easy(node, current_player): """ Simple heuristic function. """ _, y = node.get_neutron_coordinates() # Calculates the distance between the neutron and the player's home rank if current_player == PLAYER_A: return y else: ...
class Round: SYMBOLS = { "A": "rock", "B": "paper", "C": "scissors", "X": "rock", "Y": "paper", "Z": "scissors", } OUTCOMES = { ("rock", "paper"): "win", ("rock", "scissors"): "lose", ("paper", "rock"): "lose", ("paper", "scisso...
""" You arrive at the Venus fuel depot only to discover it's protected by a password. The Elves had written the password on a sticky note, but someone threw it out. However, they do remember a few key facts about the password: It is a six-digit number. The value is within the range given in your puzzle input....
num1 = int(input('Primeiro número: ')) num2 = int(input('Segundo número: ')) resul = num1 + num2 print('A soma entre {0} e {1} vale {2}'.format(num1,num2,resul))
a = int(input('Digite a altura da parede em metros: ')) l = int(input('Digite a largura da parede em metros: ')) area = a*l print('São necessários {} litros de tinta'.format(area/2))
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/6/15 17:39 ''' 需求7-5:电影票,三岁以下免费,3-12岁为10美元,超过12岁为15美元,编写一个循环,询问用户年龄 ''' while True: age = int(input('请输入你的年龄:')) if age <= 3: print('小于3岁免费观看电影') continue elif age <= 12: print('你的票价为:10美元') continue else: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/9/17 21:45 ''' break:结束最近的循环 ''' while True: a = input("请输入一个字母:") if a == "Q" or a == "q": print("循环退出") break else: print(a)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/6/12 10:43 ''' 需求7-2:餐厅订位 ''' reservations = int(input('请问你几位:')) if reservations > 8: print("目前没有空桌,需求等位,我先帮您取个号,您看可以吗?") else: print('目前不需要等位,您可以直接就餐,请跟我来。。。。')
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/9/11 9:26 ''' 需求: 输入一个分数,分数在0-100之间,90以上是A,80以上是B,70以上是C,60以上D,60以下是E ''' ''' score = int(input("请输入您的分数(0-100之间):")) grade = '' if score>100 or score<0: score = int(input("请输入您的分数(0-100之间):")) else: if score >= 90: grade = 'A' elif...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/9/3 9:34 ''' 字典是“键值对”的无序可变序列 键:是任意的不可变数据,比如:整数,浮点数,字符串,元组。但是:列表,字典,集合这些可变的对象,不能作为“键”,键不可重复 值:可以是任意的数据,并且可重复 ''' #1、{}创建 a = {"name":"yuangu","age":18,"job":"test"} print(a) #2、dict创建 b = dict(name = "yuangu",age = 18 ,job ="test") print(b) c = dict([("n...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/9/20 8:52 # 测试返回值的基本用法 ''' return 返回值的要点: 1、如果函数体中包含return语句,则结束函数执行并返回值 2、如果函数体中不包含return语句,则返回None值 3、要返回多个返回值,使用列表,元组,字典,集合将多个值“存起来”即可 ''' def test01(a,b): return a+b print(test01(10,20)) def test02(): print("python") return ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/9/12 9:15 ''' while 条件表达式: 循环体语句 需求1:用while循环打印从0-10的数字 ''' num1 = 0 while num1 <= 10: print(num1,end=" ") num1 += 1 print() print('***********************') ''' 需求2:利用while循环,计算1-100之间数据的累加和;计算1-100之间偶数的累加和,计算1-100之间奇数的累加和 ''' num2 = 1 sum...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/10/9 9:39 ''' super()关键字代表父类的定义,不是父类的对象 ''' class A: def a(self): print("aa",self) class B(A): def b(self): super().a() #A.a(self) print("bb",self) b = B() b.b()
#!/usr/bin/env python # -*- coding: utf-8 -*- __mtime__ = '2019/8/22' import io # format()基本用法 a = "名字是{0},年龄是:{1}" b = a.format("元古",33) print(b) c = "名字是{name},年龄是:{age}" d = c.format(name = "元古", age = 33) print(d) # 填充和对齐 ^居中,>右对齐 <左对齐 e = "我是:{0}, 我喜欢:{1:*>10}" print(e.format("元古", 33)) # 数字的格式化 a1 = "我的存款有...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/10/12 10:45 import copy class MobilePhone: def __init__(self,cpu,screen): self.cpu = cpu self.screen = screen class CPU: def calculate(self): print("cpu对象:",self) class Screen: def show(self): print("Screen对象...
# encoding: utf-8 # !/usr/bin/env python ''' @author: hekai @license: (C) Copyright 2013-2017, kylinos. @contact: hekai@kylinos.com.cn @software: garner @file: selection_sort.py @time: 2019/2/27 10:05 @desc: ''' import random from record import record def bubble_sort(nums): for i in range(len(nums)): ...
name = input ("what is your name?") print("nice to meet you, ",name) color = input ("what's your favorite color?") print("what a horrible taste, how could you like such a color!?") movie = input ("what is your favorite movie genre?") print("I beleive we will never be compatible, you like the worst things") coding = inp...
#Average squares import time start_time = time.time() sq_size = 6 #Get value of pixel from list def get_pixel(x, y): return pixels[x + y*width] #Load file pixels = open("mandelbrot_big.txt", "r").read().split("\n") pixels = pixels[:-1] pixels = list(map(int, pixels)) width = pixels[0] height = pixels[1] pixels...
import random, math, game from Dict import Dict class Item(Dict): def __init__(self, name, rarity, quality=None, dob=game.time(), max_age=None, durability=100, stacksize=1, **kargs): """ Parameters: ----------- name : str Name of the item rarity : float ...
from wordsearch import list_to_tuple def list_to_tuple_checker(): """ check the function list_to_tuple by going over its items and sub items :return: True if all tests pass. False otherwise """ flag = True lst = ['dog','cat','Cat','DOG','dog'] histogram_tuple = list_to_tuple(lst) ...
class Board: """ Add a class description here. Write briefly about the purpose of the class """ def __init__(self,height=7,width=7): """ A constructor for Board object :param height: 7 :param width: 7 """ self.__cars = [] self.__height = heig...
n=int(input("введите число ")) def avto(i): b=1 a=i while a>=10: #узнаю сколько знаков в числе b=b+1 a=a//10 b=10**b if i==(i**2)%b: print(i**2,i) g=1 while g<=n: avto(g) g=g+1
a=float(input("введите длину стороны a ")) b=float(input("введите длину стороны b ")) c=float(input("введите длину стороны c ")) if (a+b>c) and (a+c>b) and (b+c>a) and (a>0) and (b>0) and (c>0): print("такой треугольник существует") else: print("такой треугольник не существует")
class Solution: def reversedLinkedList(self, head: ListNode): """ what we are gonna do here, instead of reversing the actual value, we will be reversing the pointers. we will point the first pointer to None, since we know that by definition, the end of the linked list is pointing to None or null. ...
def show_balance(balance): print("your current balance is: ", float(balance)) def deposit(balance): amount = input("Enter amount to deposit: $") return float(amount) + balance def withdraw(balance): amount = input("Enter amount to withdraw: $") return balance - float(amount) def logout(name): ...
def quickSort(alist): quickSortHelper(alist,0,len(alist)-1) def quickSortHelper(alist,first,last): if first<last: splitpoint = partition(alist,first,last) quickSortHelper(alist,first,splitpoint-1) quickSortHelper(alist,splitpoint+1,last) def partition(alist,first,last): pivotvalue = a...
from pdb import set_trace as bp def searchRange(A, B): # set start and end # get mid point # if mid == target: # check forward and backward till it matches # if mid > target: # end = mid - 1 # if mid < target: # start = mid + 1 if len(A) <= 1: return A sta...
class Solution: # @param A : tuple of integers # @return an integer def hammingDistance(self, A): xor = 0 pairs = ((i, j) for i in A for j in A) for i, j in pairs: i = int(format(i, 'b')) j = int(format(j, 'b')) summ = sum(list(map(int, st...
class NotListError(Exception): pass def zbuduj_zdania(lista): if not isinstance(lista, list): raise NotListError wynik = "" for zdanie in lista: for slowo in zdanie: if zdanie.index(slowo) == 0: wynik += slowo.capitalize() + " " elif zdanie.inde...
""" Plot a visual representation of an SVD -------------------------------------- Figure 7.3 Singular value decomposition (SVD) can factorize an N x K matrix into :math:`U \Sigma V^T`. There are different conventions for computing the SVD in the literature, and this figure illustrates the convention used in this text....
# Return Kth to Last: Implement an algorithm to find the kth to last element of a singly linked list. import unittest class Node: def __init__(self, data, next=None): self.data, self.next = data, next def find_kth_to_last(head, k): node = head follow = head for n in range(k): if not...
#ntersection: Given two (singly) linked lists, determine if the two lists intersect. #Return the intersecting node. Note that the intersection is defined based on reference, not value. #That is, if the kth node of the first linked list is the exact same node (by reference) as the jth node of the second linked list, t...
class GraphNode: left = None right = None def __init__(self,data): self.data = data def setLeft(self, node): self.left = node def setRight(self, node): self.right = node class Graph: def __init__(self, root): self.root = root self.adjacencyDict = { self.root: [] } def s...
# Given a circular linked list, implement an algorithm that returns the node at the beginning of the loop. DEFINITION # Circular linked list: A (corrupt) linked list in which a node's next pointer points to an earlier node, # so as to make a loop in the linked list. import unittest class Node: next = None d...
def cipher(input): ret = '' for element in input: ret += chr(219 - ord(element)) if element.islower() else element print(ret) str = "Atbash is a simple substitution cipher for the Hebrew alphabet." cipher(str)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Sep 11 08:27:55 2021 @author: siddharthgehlot """ #given an array find if it contains integers array=[1,2,3,4] def duplicates(array): map={} for i in range(len(array)): if array[i] in map: map[array[i]]+=1 if ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 9 13:16:11 2021 @author: siddharthgehlot """ # VALIDATE BINARY TREE class Node: def __init__(self,data,parent): self.data = data self.leftChild = None self.rightChild = None self.parent = parent self.vi...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Sep 10 15:53:53 2021 @author: siddharthgehlot """ #boat required to carry each person person = [3,2,3,2,1,2,2] limit = 3 def noBoats(person,limit): s=0 i=0 n=0 while i<len(person): s+=person[i] ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Sep 12 10:01:57 2021 @author: siddharthgehlot """ # add two numbers of linked list class Node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Sep 12 10:19:20 2021 @author: siddharthgehlot """ #remove nth node from the end of list #n = 2 #input 1>2>3>4>5 #output 1>2>3>5 class Node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __in...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 31 12:04:06 2021 @author: siddharthgehlot """ string = 'ab#d#efg##' def typedoutstr(string): array = list(string) st =[] st1='' for n,i in enumerate(array): if i!='#': st.append(i) else: ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 31 17:55:19 2021 @author: siddharthgehlot """ #reverse a linked list class Node: def __init__(self,data): self.data = data self.next = None class linkedlist: def __init__(self): self.head =None def i...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Sep 11 09:33:44 2021 @author: siddharthgehlot """ #compare how many tuples are there such that a=[1,2] b=[-1,2] c=[1,-2] d = [-1,-2] sum1=0 map={} for i in range(len(a)): for j in range(len(b)): s = a[i]+b[j] map[s]=0 for k in ran...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 6 18:57:37 2021 @author: siddharthgehlot """ #linked list reverse M to N class Node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): se...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Sep 10 10:32:17 2021 @author: siddharthgehlot """ #KNIGHT PROBABILTY IN CHESSBOARD chess_size = 6 chessboard = [[0 for _ in range(chess_size)] for _ in range(chess_size)] row = 0 col = 0 direction = [[2,1],[2,-1],[1,2],[1,-2],[-2,1],[-2,-1],[-1,2],[-1...
number1=float(input('Enter one number: ')); number2=float(input('Enter other number:')); print(f'The sum between the first number and the second number was {number1+number2}');
height=float(input('Enter your height: ')); print(f'Your ideal weight is {(72.7*height)-58}');
# from math import pi # print [str(round(pi,x)) for x in range(10)] # print str([1,2,3,4]) # from math import pi # print [str(round(pi,i)) for i in range(1,6)] #amazing one liners # print [(x,y) for x in range(5) for y in range(10) if x!=y] # #equivalence # coms = [] # for x in range(5): # for y in range(10)...
import sys def isCaptionText(lineIndex): if lineIndex <= 0: return False # the text is on every third line starting from the second line return (lineIndex - 1)%3 == 0 if len(sys.argv) < 3: print('Arguments: [source sbv filename] [destination txt filename]') sys.exit() with open(sys.argv...
from argparse import ArgumentParser from .weather import Weather import sys def main(): PARSER = argparse.ArgumentParser() PARSER.add_argument( "-unit", default="c", choices=["c","f"], help="Units C or F." ) PARSER.add_argument( "-f", "--forecast", ...
from fractions import Fraction def digit_exceeds(nominator,denominator): #WORKS #returns True if the number of digits of the numerator exceeds the one of the denominator i = 0 while True: if nominator//(10**i)>0 and not denominator//(10**i)>0: return True if denominator//(10**i)>0 and not nominator//...
import sys import math class great_circle_calculator(object): """ EXECUTION: python pemdasq1.py <minlat> <maxlat> <minlng> <maxlng> Constraints: Latitude and longitude values are in decimal degrees as abs(0<=latitudes<89) and abs(0<=longitudes<180) minlat...
#!/usr/bin/env python # -*- coding: utf-8 -*- import xlrd import numfmt import locale def format_number(f, cell, wb): xf = wb.xf_list[cell.xf_index] fmt_key = xf.format_key fmt = wb.format_map[fmt_key] s_fmt = fmt.format_str a_fmt = numfmt.extract_number_format(s_fmt) if a_fmt: s_f = numfmt.format_nu...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Dec 27 22:34:41 2018 @author: felix """ import random class RandMemory: def __init__(self, start, stop): self.lowest = start self.highest = stop self._history = [] @property def get(self): x = rand...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @created: 23.06.19 @author: felix """ import abc class ImmutableMeansImmutableError(Exception): pass class ImmutableParent(abc.ABC): def __init__(self, **kwargs): for k, v in kwargs.items(): # mark each attribute as property helps to pr...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Dec 27 22:35:32 2018 @author: Reuven M. Lerner """ from exercise13 import RandMemory def test_empty(): r = RandMemory(1, 100) assert r.lowest == 1 assert r.highest == 100 assert r._history == [] assert r.history() == [] def test_t...
""" Given a list of integers `lst`, any integer with a frequency that is equal to its value is considered a **lucky integer**. Write a function that returns the lucky integer from the array. If the array contains multiple lucky integers, return the largest one. If there are no lucky integers return -1. **Example 1**:...
"""Python functions for JavaScript Trials 1.""" def output_all_items(items): for item in items: print(item) def get_all_evens(nums): even_numbers = [] for num in nums: if num % 2 == 0: even_numbers.append(num) return even_numbers def get_odd_indices(items): odd_i...
numpy.arange numpy.arange([start, ]stop, [step, ]dtype=None) Return evenly spaced values within a given interval. Values are generated within the half-open interval [start, stop) (in other words, the interval including start but excluding stop). For integer arguments the function is equivalent to the Python built-in ...
def sorted(iterable[, cmp[, key[, reverse]]]): ''' ''' pass ################################################################################ #Python内置的sorted()函数 >>> sorted([36, 5, 12, 9, 21]) [5, 9, 12, 21, 36] #sorted()函数也是一个高阶函数,它还可以接收一个比较函数来实现自定义的排序。比如, #如果要倒序排序,我们就可以自定义一个reversed_cmp函数: def reversed_cmp...
--> Python Objects Python uses the object model abstraction for data storage. Any construct that conta- ins any type of value is an object. All Python objects have the following three cha- racteristics: an identity, a type, and a value. IDENTITY Unique identifier that differentiates an object from all others. ...
Forward References Like some other high-level languages, Python does not permit you to reference or c- all a function before it has been declared. def foo(): print 'in foo()' bar() def bar(): print 'in bar()' >>> foo() in foo() in bar() This piece of code is fine because even ...
#coding=utf-8 ##################################################################################### ############ self #类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称,但是在调 #用这个方法的时候你不为这个参数赋值,Python会提供这个值。这个特别的变量指对象本身,按 #照惯例它的名称是self。虽然你可以给这个参数任何名称,但是 强烈建议 你使用self这个名称 #你一定很奇怪Python如何给self赋值以及为何你不需要给它赋值。举一个例子会使此变得清晰。 #假如你有一个类称为M...
# http://shelly-kuang.iteye.com/blog/797713 Pythonģѧϰʹ optparse в class OptionParser(...): # optparse.OptionParser def OptionParser.add_option(option): pass def add_option(*opt_str, attr=value, ...): pass --> 쳣 | 쳣û...
def filter(function, iterable): ''' Construct a list from those elements of @iterable for which @function returns true. @iterable may be either a sequence, a container which supports iteration, or an it- erator. If @iterable is a string or a tuple, the result also has that type; otherw- ise it is always a l...
# class Solution: # # @param A, a list of integers # # @return an integer # def jump(self, A): class Solution: # We use "last" to keep track of the maximum distance that has been reached # by using the minimum steps "ret", whereas "curr" is the maximum distance # that can be reached by using "ret+1" steps....
def solve(N,M,zip_of,flights): def still_possible(): # still_possible() asks if there is still some way to visit all # the cities given the current configuration hypothetically_visited = set(visited) # set of cities we can hypothetically visit. def recurse(city): # dfs to try to hypothetically visit all ...
""" Builds a hexagonal lattice of size (n_row, n_col) on a torus, periodic boundary conditions. """ import numpy as np from matplotlib import pyplot as plt from numba import njit # # # # Numba optimized functions # # # # # Numba optimized functions are defined outside the HexagonalLattice class, # since numba canno...
length = int(input("How many students do you have?")) listOfStudents = [] while length: students = {} name = input("Students name: ") if not name: print("Invalid name, try again..") name = input("Students name: ") students["Name"] = name grade = input("Students garde: ") while ...
class BankAccount: def __init__(self): self.int_rate = 1/100 self.balance = 0 def deposit(self, amount): self.balance += amount return self def withdraw(self, amount): if self.balance < amount: print("Insufficient funds: Charging a $5 fee" ) ...
# input will come from buttons and an input field # all output for the game will be printed in the console import random import simplegui # helper function to start and restart the game k = 0 # k is a variable to determine if we should use range100 # and if we should use a Blank line before new game def new_game(): ...
from binascii import hexlify, unhexlify from typing import Optional from main import Solution from p39 import RSA, invmod def kth_root(n: int, k: int, rounded: bool = False) -> Optional[int]: bits = len(bin(n)[2:]) mn, mx = (2**(bits // k)), (2**(bits // k + 1)) mid = (mx + mn) // 2 guess = mid**k ...
import requests import json #application programming interface(API) #swiggy uses api to communicate between FB,google,geolocation,payment getaway etc #client to API has two requests , thus GET(to just get data) and POST(to tell some information to API) #API has addresss in the form of endpoint #api sends a respon...
def add_to_five(number): """Returns ammount to be added to form a nearest 5""" return 5 - (number % 5) def sub_to_five(number): """Returns ammount to be subtracted to form a nearest 5""" return number % 5 def efficient_change(payouts): """Calculate the most efficient ammounts of bank notes""" ...
test = "hello world"; print (test) test1 = test.split(" ")[1] print ( " Say hello "+ test1 + "jio") print(str('test')) print(int('5')) print(len(["test", "test1"])) print(sorted([1,5,6,8,7,12,10,1,15,88,85])) print(sorted(['shashi', "test", "Ankit","Nitin"]))
def return1(num1, num2): return num1+num2 print1 = return1(5,7) print2 = return1(10*10,10) print(print1, print2)
size = input("Input triangle size\n"); for i in range(size): stars = '' for j in range(i + 1): stars += '*' print(stars + '\n')
# ### FIRST_PASS: # def single_number(arr): # ''' # Input: a List of integers where every int except one shows up twice # Returns: an integer # ''' # # Your code here # # create a counter # count = 0 # # loop through array and update counter # for i in arr: # # compare coun...
# O(n^2) runtime on brute force approach, can we improve? # Is there a data structure that would help? # A dict help by allowing to check for duplicate values # Sets are also an option # As we loop, save the fact that we saw this value # If we see it again, then remove them def single_number(arr): ''' Input:...
class Solution(object): def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ if len(nums) == 0: return [[]] results = [] for idx in range(len(nums)): self.recursive_permute(nums[:idx]+nums[idx+1:], [nums[idx]...
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(S): # write your code in Python 3.6 longestString = 0 currentString = 0 expectingB = False for letter in S: if (not expectingB) and (letter == "A"): currentString += 1 ...