text stringlengths 37 1.41M |
|---|
#----------------------------selection sort---------------------------------------
a=[]
for i in range(0,5):
q=int(input("the input is :"))
a.append(q)
print(a)
for i in range(len(a)):
min_index=i
for j in range(i+1, len(a)):
if a[min_index]>a[j]:
min_index=j
... |
from functions import Maze
n = int(input("Quanti labirinti vuoi generare? "))
for i in range(0, n):
numRows = int(input("Inserisci il numero di righe "))
numColumns = int(input("Inserisci il numero di colonne "))
G = Maze.generateGraph(numRows, numColumns)
print("Il numero dei vertici ", G.number_of_no... |
from pprint import pprint
# PASTE THE CHOSEN NUMBERS HERE
numbers = [
[1, 16, 27, 40, 44, 1],
[1, 16, 27, 40, 44, 7],
[1, 16, 27, 40, 44, 15],
[6, 16, 27, 33, 44, 1],
[6, 16, 27, 33, 44, 7],
[6, 16, 27, 33, 44, 15],
[8, 16, 27, 33, 44, 1],
[8, 16, 27, 33, 44, 7],
[8, 16, 27, 33, 44, 15]
]
# PASTE T... |
"""
Learn about dictionaries
"""
from pprint import pprint as pp
def main():
"""
Test function
:return:
"""
urls = {
"google": "www.google.com",
"yahoo": "www.yahoo.com",
"twitter": "www.twitter",
"wsu": "weber.edu"
}
print(urls, type(urls))
# Access by k... |
"""
Generator Objects are a cross between comprehensions and generator functions
Syntax: Similar to list comprehension, but with parenthesis:
(expr(item) for item in iterable)
"""
from list_comprehensions import is_prime
def main():
"""
Test function
:return:
"""
# list with first 1 million sq... |
"""
File learn about collection: Tuples, Strings, Range, List, Dictionaries, Sets
"""
def do_tuples():
"""
Practice tuples
:return: nothing
"""
# Immutable sequence of arbitrary objects
# Use () to define a tuple
t = ("Ogden", 1.99, 2)
print(t, type(t))
print("Size ", len(t))
p... |
"""
Simulate 6000 rolls of a die (1-6)
"""
import random
import statistics
def roll_die(num):
"""
Random roll of a die
:param num: number of rolls
:return: a list of frequencies.
Index 0 maps to 1
Index 1 maps to 2
etc
"""
freq = [0] * 6 # initial val to 0
for roll in range(nu... |
'''
On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).
Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor,
and you can either start from the step with index 0, or the step with index 1.
'''
class Solution:
... |
'''
191. Number of 1 Bits
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.
'''
class Solution(object):
de... |
'''
26. Remove Duplicates from Sorted Array
Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
2 pointers
'''
class Solu... |
'''
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
'''
class Solution:
def dfs(self, i, j, board,... |
import unittest
from typing import Optional, List, Union
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left: Optional[TreeNode] = None
self.right: Optional[TreeNode] = None
class Tree:
def __init__(self, data: Union[List, TreeNode, None... |
'''
find how many combinations that sum up to a given total
None negative elements
'''
def rec(arr, total, last_index):
'''
Recursive function that add up to a given total
'''
if total==0:
return 1
elif total < 0:
return 0
elif last_index<0:
return 0
return rec(arr... |
'''
Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
Each row must contain the digits 1-9 without repetition.
Each column must contain the digits 1-9 without repetition.
Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without rep... |
'''
796. Rotate String
We are given two strings, A and B.
A shift on A consists of taking string A and moving the leftmost character to the rightmost position. For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. Return True if and only if A can become B after some number of shifts on A.
Exampl... |
# 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 inOrder(self, root, bstArr):
if not root:
return
if root.left:
self.inOrder(r... |
'''
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \... |
'''
a - 1
b - 2
...
z - 24
given a number, return how many possible ways to decode it
'''
from functools import wraps
import time
def timmer(func):
@wraps(func)
def clock(*args, **wargs):
start = time.clock()
print(func(*args, **wargs))
end = time.clock()
print("Time duration o... |
''' Given an 2D board, count how many battleships are in it. The battleships are represented with 'X's, empty slots are represented with '.'s. You may assume the following rules:
You receive a valid board, made of only battleships or empty slots.
Battleships can only be placed horizontally or vertically. In other words... |
"""
Given an array, rotate the array to the right by k steps, where k is non-negative.
"""
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
while k > 0:
... |
'''
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Floyd's cycle-finding algorithm
https://en.wikipedia.org/wiki/Cycle_detection#Tortoise_and_hare
'''
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.v... |
'''
You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.
The null node needs to be represented by empty parenthesis pair "()".
And you need to omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship between the str... |
"""
Four divisors
"""
import math
from typing import List
class Solution:
def divisors(self, n:int) -> List[int]:
"""
this is the core algo to list all the divisors with O(sqrt(n)) instead of O(n)
"""
i = 1
result = []
while i <= math.sqrt(n):
if n % i == ... |
'''
19. Remove Nth Node From End of List
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next:ListNode|None = None
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
... |
'''
We can determine how "out of order" an array A is by counting the number of inversions it has. Two elements A[i] and A[j] form an inversion if A[i] > A[j] but i < j. That is, a smaller element appears after a larger element.
Given an array, count the number of inversions it has. Do this faster than O(N^2) time.
Y... |
"""
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
#... |
"""
154. Find Minimum in Rotated Sorted Array II
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
The array may contain duplicates.
Would allow duplicates affect the run-time complexity? ... |
"""
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
"""
class Solution:
def dfs(self, result, s, temp_set):
print(len(temp_set), s)
if len(temp_set)>4 and s:
return
if len(temp_set)==4 and not s:
print('.'.jo... |
'''
Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below.
Note:
You may use one character in the keyboard more than once.
You may assume the input string will only contain letters of alphabet.
'''
class Solution:
d... |
#!/bin/python
'''
Utilized a concept of stack
'''
class Solution:
def calPoints(self, ops):
"""
:type ops: List[str]
:rtype: int
"""
round_points=[0,0]
for op in ops:
if op == 'C':
round_points.pop()
elif op=='+':
... |
'''
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview... |
'''
Matrix:
Count the number of islands in a matrix
'''
class Solution:
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
def getIsland(i,j):
if 0<=i<len(grid) and 0<=j<len(grid[0]) and grid[i][j]=='1':
grid[i][j]='0'
... |
import random
import unittest
userList = []
def listUsers():
for x in userList:
print(x.accountID)
groupList = []
def listGroups(self):
for x in Group.groupList:
print("group ", x.groupID)
def storeAccount(account, password, file): #function to store user in database
f... |
#Script constructs the plural of an English noun according to various plural rules
#Not conclusive, some rules not taken care of
#use of iterators
import re
def build_apply_match_functions(pattern, search, replace):
'''A closure function that build two function dynamicaly;
match_rule => matches a pattern agai... |
class Operators:
def __init__(self):
self.MONTHLY = False
self.DAILY = False
self.END_OF_MONTHLY = False
self.operations = []
self.currentDay = None
self.currentMonth = None
self.currentYear = None
def init_date(self, year, m... |
from stack import Stack
def reverse(input_string):
s = Stack()
print(input_string[::-1])
for i in range(len(input_string)):
s.push(input_string[i])
reverse_string = ""
while not s.is_empty():
reverse_string += s.pop()
return reverse_string
print(reverse("siddhartha")) |
n=int(input("n="))
"""def nchiziq(n):
txt=''
for i in range(n):
txt+='-'
print(txt)"""
# 2-usul
def nchiziq(n):
print("-"*n)
nchiziq(n) |
# berilgan n sonidan kicik bolgan sonlarning darajasi n sonidan kichik sonlarni chiqarish
n=int(input("n="))
def daraja(n):
qiymat=[]
for i in range(1,n):
if i**2<n:
qiymat.append(i)
return qiymat
print(daraja(n))
|
number=(1,2,3,4,5,6,9,8,7,4,6,5)
print(number.count(5))
print(number.index(9))
print(any(number))
print(max(number))
print(min(number))
print(len(number))
print(sorted(number))
print(sum(number))
|
def PowerA3(n):
return n**3
A=1.1
B=2.2
C=3.3
D=1
E=2
print(PowerA3(A))
print(PowerA3(B))
print(PowerA3(C))
print(PowerA3(D))
print(PowerA3(E)) |
#1-misol 10 raqmini chiqarish
numbersList = [[1, 2, 3, 4], [0, [1, 2, [4, 5, [10, 11]], 4], 5], 12]
print(numbersList[1][1][2][2][0])
#2-miol 5 ni chiqaring
numbersList1=[[1,2,3],[4,5,6],[7,8,9]]
print(numbersList1[1][1])
|
# # namunaviy masala
# a = [1, 2, 3, 4]
# b = [1, 2, 3, 4]
# c = [1, 2, 3, 4]
#
#
# # ro'yhatlarni 2 dan katta elementlarini ekranga chiqaring
# def myFunction(x):
# for i in x:
# if i > 2:
# print(i)
#
#
# myFunction(a)
# myFunction(b)
# myFunction(c)
""" funcksiyalar va protseduralar """
# fu... |
"""kortej berilgan ularning toq o'rindagi elementlari """
d=(1,2,3,4,5,6)
juft=[]
for i in range(1,len(d),2):
juft.append(d[i]**2)
print(tuple(juft))
|
x=int(input("x kiriting="))
y=int(input("y kiriting="))
if x%2==0 and y%2==0:
print(f"{x} juft son {y} juft son")
elif
x % 2 != 0 and y % 2 == 0:
print(f"{x} toq son {y} juft son")
elif
x % 2 != 0 and y % 2 == 0:
print(f"{x} toq son {y} juft son")
else:
print(f"{x} toq son {y} toq son")
|
class Player:
def __init__(self, piece):
self.piece = piece
def move(self, board):
valid = False
while not valid:
try:
position = input("Enter column to play: ")
if int(position) >= board.cols:
raise ValueError
... |
def sum(a):
global n
for i in range(a+1):
n = n + i
return n
n = 0
print(sum(5))
|
class goldar():
def __init__(self, antiA, antiB, antiAB, antiD, darah, rhesus):
self.antiA = antiA
self.antiB = antiB
self.antiAB = antiAB
self.antiD = antiD
self.darah = darah
self.rhesus = rhesus
def findgoldar(self):
if (self.antiA == "Mengg... |
class KAryLevel:
def __init__(self):
self.isLeaf = True
self.size = 0
self.rootNode = None
class KAryNode:
def __init__(self,val,right_of_root):
self.right_of_root = False
self.data = val
self.left = None
self.right = None
self.left_level = None
... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
# Hyper parameters
step_size = 0.01 # How much should the network weights change in case of a wrong prediction?
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# Cons... |
# TO-DO: Complete the selection_sort() function below
def selection_sort(arr):
# loop through n-1 elements
for i in range(0, len(arr) - 1):
cur_index = i
smallest_index = cur_index
# TO-DO: find next smallest element
# (hint, can do in 3 loc)
for j in range(i+1, len(arr))... |
"""
Provides class for checking if a bot is shadow banned
"""
try:
from urllib.request import urlopen
from urllib.error import HTTPError
except:
from urllib2 import urlopen
from urllib2 import HTTPError
from .utils import ColoredOutput
import os
class Shadow(object):
"""
Class providing metho... |
def missingel(slist):
# returns the missing element of a sorted list
# considering mini and maxi variables, we fix the "front and back seats" issue
mini = slist[0]
maxi = slist[-1]
for i in range(mini, maxi):
if not (i in slist):
return i
# this should not be reached
r... |
#SLOT: 4
#Write a program to find the nth value in the series.
#Problem description
#here position starts at ( 0,0 ) and it will move in the direction right, top, left , bottom at the multiples of 10 .
#( consider a graph with origin and directions as x, y, -x, -y on moving in x, y it will be positive term and... |
list1 = [10, 20, 30, 40, 51, 55, 20, 32, 521, 45, 84, 54, 65, 625]
list2 = [10, 20, 30, 40, 51, 55, 20, 32, 521, 45, 84, 54, 65, 740]
# bubble sort
def bubble_sort(lister):
for i in range(len(lister) - 1):
for j in range(len(lister) - i - 1):
if lister[j] > lister[j + 1]:
... |
__author__ = 'asdis'
from random import *
from ascending import *
from descending import *
table = []
for i in range (0, 50):
table.append(randrange(0, 99))
print (table)
choice = int(input("wybierz sortowanie rosnace (1) lub malejace (2): "))
if choice == 1:
print (ascending(table))
elif choice == 2:
pri... |
import sys
# Defining the Grader class
class Grader:
# Creating the constructor
def __init__(self):
# Getting the user data from the command line in the constructor
self.name = raw_input("What is your name? ")
self.assignment_name = raw_input("What is the name of your assignment? ")
self.grade = float(raw_in... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
visited=dict()
def getneighbours(edgelist,v):
for key in edgelist[v]:
yield key
def dfs(graph,start):
count=0
stack=list()
stack.append(start)
while len(stack)!=0:
v=stack.pop()
if not visited.ha... |
# Python3 implementation of program to count
# minimum number of steps required to measure
# d litre water using jugs of m liters and n
# liters capacity.
def gcd(a, b):
if b==0:
return a
return gcd(b, a%b)
''' fromCap -- Capacity of jug from which
water is poured
toCap -- Capacity of jug to which
water is ... |
#list program
list1 = ['physics', 'chemistry', 'maths', 'science', 'social', 'zoology', 'geography', 'botany', 'computer science','economics'];
print(list1)
#perform slicing
list1[1:4]
#perform repeatition using * operator
newlist = [list1] * 2
#concatenate two list
new = list1+newlist |
I)
#program to check prime or not
num = int(input("Enter a number to check prime or not: "))
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,... |
"""
面试题15:二进制中1的个数
题目:请实现一个函数,输入一个整数,输出该数二进制表示中1的个数。例如
把9表示成二进制是1001,有2位是1。因此如果输入9,该函数输出2
"""
def num_of_1(n):
ret = 0
while n:
ret += 1
n = n & n-1
return ret
if __name__ == '__main__':
print(num_of_1(12)) |
'''
题目:请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个
格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路
径不能再进入该格子。 例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含
"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
'''
from numpy import *
import numpy as np
#主函数
def has_path(matrix,rows,cols,s):
... |
def printEmployes(empList):
print "There are {0} employees".format(len(empList))
for emp in empList:
print emp
employees = [
"Mac", "Yasmin", "Gail", "Linda", "Doug", "Trevor", "Kalvin", "Susan"
]
while True:
printEmployes(employees)
remove = raw_input("Who do you wanna remove?")
if re... |
def namesFilledIn(name):
if len(name) == 0:
return False
return True
def namesAtLeast2(name):
if len(name) < 2:
return False
return True
def validID(ID):
length = len(ID)
if length != 7:
print "ID Not the right length"
return False
if "-" not in ID:
... |
def main():
try:
f = open("C:/Users/Student 2/Documents/Assignment1.txt", "r")
print(f.read(1))
print(f.readline())
print(f.read())
f.close()
except:
print("Error opening file")
f2 = open("C:/Users/Student 2/Documents.txt", "r")
my_list = []
for line ... |
first_name = str(input("Enter your name "))
current_balance = float(input("Enter your current balance in the bank account: "))
deposited_amount = float(input("Enter the deposited amount: $"))
total = current_balance + deposited_amount
print (first_name, total "${0.2f}.format(total))
|
# Based on: https://github.com/ageitgey/face_recognition/blob/master/examples/web_service_example.py
# This is a _very simple_ example of a web service that recognizes faces in uploaded images.
# Upload an image file and it will check if the image contains a known face.
# Pictures of known faces must be stored in the ... |
#!/usr/bin/env python3
from math import floor
def main():
vals = input().split()
carbon = int(vals[0])
hydrogen = int(vals[1])
oxygen = int(vals[2])
carbon_diox = 0.25 * (2 * oxygen - hydrogen)
glucose = (carbon - carbon_diox) / 6
water = -carbon + carbon_diox + hydrogen / 2
if wate... |
#!/usr/bin/env python3
# Jonathan De Leon
# CSCI 531 Applied Cryptography
# April, 2021
import sys
import random
import math
import json
sys_random = random.SystemRandom()
# Default rounds to 40 due to following stack overflow
# https://stackoverflow.com/questions/6325576/how-many-iterations-of-rabin-miller-should-i... |
'''
Linked List 의 장단점
장점은 배열처럼 정해진 데이터 공간을 할당하지 않아도 사용가능하다는 점
단점은 pointer 를 위한 별도의 주소 공간이 필요하기 때문에 저장공간의 효율 자체가 높은 편은 아니고,
연결된 주소 위치를 찾는데 있어서 접근 시간이 필요하므로 접근 속도가 늦어짐
또한 중간 노드 삭제시 연결을 재구성해야됨
'''
class Node:
def __init__(self, data):
self.data = data
self.next = None
node1 = N... |
'''
Insertion Sort
삽입 정렬은 Bubble Sort 나 Selection Sort 처럼
모두 자리를 바꾸는 형식이 아니라,
비교를 하려고 하는 현 위치 인덱스 이하의 인덱스들에 대한 원소들 비교를 수행해서
자신이 들어갈 위치를 선정해주는 정렬알고리즘
아래의 코드는 오름 차순 예시임
'''
def InsertionSort(data):
for i in range(len(data) - 1):
j = i
while(j >= 0 and data[j] > data[j + 1... |
'''
소수 찾기 코드
가장 기본적인 내용만을 사용한 파이썬 코드
(1과 자기 자신의 수 외의 수로 나눠지는 경우 소수가 아님을 활용하여
입력된 특정한 숫자 하나가 소수인지 아닌지 판별하는 단순한 코드)
'''
def FindPrime(x):
for i in range(2, x):
if(x % i == 0):
return False
return True
print(FindPrime(67))
|
"""
文本序列化
将文本转化成对应的张量才能进行处理
"""
class WordSequence():
UNK_TAG = "<UNK>"
PAD_TAG = "<PAD>"
# unk用来标记词典中未出现过的字符串
# pad用来对不到设置的规定长度句子进行数字填充
UNK = 0
PAD = 1
def __init__(self):
# self.dict用来对于词典中每种给一个对应的序号
self.dict = {
self.UNK_TAG: self.UNK,
self.PAD_T... |
"""
Cookie Clicker Simulator
"""
import simpleplot
import math
# Used to increase the timeout, if necessary
import codeskulptor
codeskulptor.set_timeout(20)
import poc_clicker_provided as provided
# Constants
SIM_TIME = 10000000000.0
#SIM_TIME = 10000.0
class ClickerState:
"""
Class to keep track of the ga... |
"""
2.1 Write a Python program using function concept that maps list of words into a list of integers
representing the lengths of the corresponding words.
Hint: If a list [ ab,cde,erty] is passed on to the python function output should come as [2,3,4]
Here 2,3 and 4 are the lengths of the words in the list.
"""
def l... |
try:
print('try...')
r = 10 / 2
print('result:', r)
except ZeroDivisionError as e:
print('except:', e)
except ValueError as e:
print('ValueError:', e)
else:
print('no error!')
finally:
print('finally...')
print('END')
import logging
def foo(s):
return 1 / int(s)
def bar(s):
return... |
#1
# def foo(s):
# n = int(s)
# assert n != 0, 'n is zero'
# return 10 / n
#
# def main():
# foo('0')
#
# main()
# 2
# import logging
# logging.basicConfig(level=logging.INFO)
# s = '0'
# n = int(s)
# logging.info('n = %d' % n)
# print(10 / n)
#3
import pdb
s= '0'
n = int(s)
pdb.set_trace()
print(1... |
# merge sort algorithm
# divide and conquer algorithm, once broken down, compares indexes and merges back into one array
# recursive function, calls itself to keep dividing itself till size becomes one
def merge_sort(arr): # this whole chunk breaks down the array
if len(arr) > 1:
# finds the mid of the a... |
# 一些乱七八糟的函数与库
from itertools import combinations
from itertools import permutations
import csv
def output(A):
'''
输出矩阵
'''
for i in range(len(A)):
for j in range(len(A[i])):
print(A[i][j], end = ' ')
print('\n')
for i in range((len(A[0])-1)*5+1):
... |
p = float(input('请输入税前月收入:'))
i = float(input('请输入五险一金:'))
def CalcOld():
threshold = 3500
pt = p - i - threshold
tax = 0
if pt > 0:
if pt > 80000:
tax = pt*0.45 - 13505
elif pt > 55000:
tax = pt*0.35 - 5505
elif pt > 35000:
tax =... |
__author__ = 'aferreiradominguez'
class Persoa:
"""Clase que definae unha persoa """
def __init__(self, nome):
self.nome = nome
def sauda(self):
print("Ola " + self.nome)
persona = Persoa("aaron")
persona.sauda()
class Oficio:
"""Clase que define oficio"""
def __init__(self,... |
# -----------------------------------------------------START------------------------------------------------------------
# function initialised
def speedCheck(speed):
if 70 > speed:
print("OK")
print('\n')
else:
demPoint = (speed - 70) / 5
if demPoint > 12:
print("L... |
# ------------------------------------------------------START-----------------------------------------------------------
# string user-initialised
inputStrng = input("Enter the string\n")
# string length
strngLen = len(inputStrng)
# values initialised
wordCount = 1
# logic
for i in range(0,strngLen,1):
if input... |
name = ('mudit','deepak','riya','rahul','mudit')
# tuple initiated
print(name)
# tuples are immutable whereas lists are mutable
# counting function
total = name.count('mudit')
# count() will count the data in the tuple
print("total count of mudit in the tuple :",total)
# converting tuple into list
lname = list(n... |
import numpy as np
from module import Module
class Linear(Module):
"""
Linear layer, including activation.
function F: R^n => R^p
"""
def __init__(self, in_dim, out_dim, activation: Module = None):
"""
W size (n, p)
b size (p,)
:param in_dim = n
:param out_... |
mylist = ["A", "B", "C"]
copied_list_1 = mylist
copied_list_2 = mylist.copy()
mylist = ["A", "X", "C"]
print(copied_list_1)
print(copied_list_2) |
# ISSUE ONE
class Restaurant():
""""
1.Initialize the class with the attributes
name, type_restaurant, address. This info comes through the paramerters.
2. add and atribute called number_people_served and
initialize it with zero.
"""
def __init__(self,name,type_restaurant,address):
self.name=na... |
import sqlite3
from selenium import webdriver
from bs4 import BeautifulSoup
conn = sqlite3.connect("covid_database.sqlite")
cur = conn.cursor()
cur.executescript(
"""
DROP TABLE IF EXISTS Covid;
CREATE TABLE Covid(
country TEXT UNIQUE,
cases INTEGER,
new INTEGER
);
"... |
from socket import * # Socket goodies
from Prime import is_prime
# Set up server port address and socket
server_port = 12000
server_socket = socket(AF_INET, SOCK_STREAM) # SOCK_STREAM indicates TCP
# Bind the server port address to the socket to give it an identity
server_socket.bind(('', server_por... |
"""Customers at Hackbright."""
class Customer(object):
"""Ubermelon customer."""
# TODO: need to implement this
def __init__(self, firstname, lastname, email, password):
self.email = email
self.password = password
def read_customer_from_file(filepath):
"""Read customer data and popu... |
# https://www.codewithharry.com/videos/python-tutorials-for-absolute-beginners-120
import pyttsx3 # it is a text-to-speech library.
import datetime
import speech_recognition as sr
# import wikipedia
import webbrowser
import os
# sapi5 is an speech api provided by microsoft to use inbuilt voices
engine = py... |
from singly import Node, SinglyLinkedList
class DNode(Node):
def __init__(self, value, prev_node=None, next_node=None):
super().__init__(value, next_node=next_node)
self.prev_node = prev_node
def set_prev_node(self, node):
self.prev_node = node
def get_prev_node(self):
r... |
"""
Compute the Sieve of Eratosthenes.
List all the prime numbers given a ``limit`` which are greater than 1 and smaller-equal
``limit``.
"""
import bisect
from typing import List
from icontract import require, ensure
@ensure(lambda a, result: result == -1 or 0 <= result < len(a))
def find(a: List[int], x: int) -> ... |
"""
Analyze the grades of the students.
Here's an example of the data
.. code-block::
111111004 5.0 5.0 6.0
111111005 3.75 3.0 4.0
111111006 4.5 2.25 4.0
Every line represents a grading of a student. It starts with her matriculation number,
followed by space-delimited grades (between 1.0 and 6.0,... |
"""
Compute a greatest common divisor (GCD) between two positive integers ``x`` and ``y``.
Please note:
1) If ``x`` is greater-equal ``y`` and ``x`` is divisible by ``y``, the GCD between
``x`` and ``y`` is ``y``.
2) Otherwise, the GCD between ``x`` and ``y`` is ``GCD(y, x % y)``.
For ``x == 36`` and ``y == 44``,... |
"""
Implement a linked list which stores integers.
Provide the following operations:
* ``add_first``,
* ``remove_first``,
* ``remove_last``,
* ``clear``,
* ``is_empty``,
* ``get`` (at index),
* ``set`` (at index), and
* ``iterate`` (over all the elements of the list).
(We substantially shortened the text of this prob... |
from typing import List, Dict
from icontract import require, ensure
LAST_STEP = 2020 #: The last relevant step of the game
@require(lambda starting_numbers: len(starting_numbers) > 0)
@ensure(lambda result: 0 <= result <= LAST_STEP - 2)
def solve(starting_numbers: List[int]) -> int:
"""Play the memory game sta... |
"""
Input: list of actions
Output: position, Manhattan distance
"""
from dataclasses import dataclass
from icontract import invariant, require, ensure
from typing import List
import re
from enum import Enum
"""
Error
ValueError: 3.977777777777778 is not a valid Orientation
"""
class Orientation(Enum):
EAST = 0
... |
# pylint: disable=line-too-long
"""
Implement a compiler for the interpreter developed in Exercise 12, Problem 1.
The program should be compiled in a language based on operand stack.
The following operations are supported:
* ``CONST c``: push the value ``c`` on the stack,
* ``LOAD v``: load the value of the variable ... |
"""
Draw the following pattern:
.. code-block::
**..**..**..
..**..**..**
**..**..**..
..**..**..**
**..**..**..
..**..**..**
You are given the size of the image (as width).
"""
import re
from typing import List
from icontract import require, ensure
from correct_programs.common import Line... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.