text stringlengths 37 1.41M |
|---|
from linkedlist import LinkedList
class Solution():
def __init__(self):
pass
def merge_k_list(self, array):
"""
Merge k sorted linked list into one sorted list
"""
merged_list = []
# get the first min head
min_index = self.get_min(array)
node =... |
def length_of_last_word(text):
"""
Given a string s consists of upper/lower-case alphabets and empty space
characters ' ', return the length of last word in the string.
NOTE: Please make sure you try to solve this problem without using library
functions. Make sure you only traverse the string once.... |
"""
question from repl.it
https: // repl.it/student/submissions/7695405
"""
def is_prime(n):
"""Determine if input number is prime number
Args:
n(int): input number
Return:
true or false(bool):
"""
for curr_num in range(2, n):
# if input is evenly divisible by the current n... |
class Node():
"""
Helper Node class for linkedlist
"""
def __init__(self, data):
"""Initialize the node with given data"""
self.data = data
self.next = None
def __repr__(self):
"""String representation of this node"""
return "Node({!r})".format(self.data)
c... |
import math
class Complex(object):
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __add__(self, no):
# (a+ib)+(c+id)=(a+c)+i(b+d)
real = self.real + no.real
imaginary = self.imaginary + no.imaginary
... |
class Extract_Date:
def __init__(self):
from datetime import datetime
import re
self.datetime = datetime
self.file_date = re.compile(u'(/[0-9]{8}/)')
def date_from_file(self, file_name):
df = self.file_date.search(file_name)
if not df:
return sel... |
def backprop(W, A, Z, y):
"""
INPUT:
W weights (cell array)
A output of forward pass (cell array)
Z output of forward pass (cell array)
y vector of size n (each entry is a label)
OUTPUTS:
gradient = the gradient with respect to W as a cell array of matrices
"""
... |
def MSE(out, y):
"""
INPUT:
out: output of network (n vector)
y: training labels (n vector)
OUTPUTS:
loss: the mse loss (a scalar)
"""
n = len(y)
loss = 0
# YOUR CODE HERE
loss = np.mean((out - y) ** 2)
return loss
def MSE_test1():
X, y = generate_d... |
def gradient(X, y, w, b):
# Input:
# X: nxd matrix
# y: n-dimensional vector with labels (+1 or -1)
# w: d-dimensional vector
# b: a scalar bias term
# Output:
# wgrad: d-dimensional vector with gradient
# bgrad: a scalar with gradient
n, d = X.shape
wgrad = np.zeros(d)
... |
# import PyTorch and its subpackages
import torch
import torch.nn as nn
from torch.nn import functional as F
# Also other packages for convenience
import numpy as np
import helper as h
import matplotlib.pyplot as plt
X = torch.zeros(3, 2) # this syntax is similar to NumPy. In Numpy, we would do np.zero(3,2)
print(X)... |
def computeK(kerneltype, X, Z, kpar=1):
"""
function K = computeK(kernel_type, X, Z)
computes a matrix K such that Kij=k(x,z);
for three different function linear, rbf or polynomial.
Input:
kerneltype: either 'linear','polynomial','rbf'
X: n input vectors of dimension d (nxd);
Z: m ... |
# how many digits are there in
# a number
import math
n = 123456
# method 1
print(len(str(n)))
# convert a number to a string
# and take its length
# method 2 (pure mathematical)
print(1 + math.floor(math.log10(n)))
# log - base 10
# Output:
# 6
# 6
|
# remove duplicates from a list
# and make sure the order is saved
data = [10,12,10,33,2,2,5,2]
result = []
values = set()
for i in data:
if i not in values:
values.add(i)
result.append(i)
print(result)
# Output:
# [10, 12, 33, 2, 5]
|
# using "filter" to select items
# bases on some condition
# here's the condition
def is_odd(x):
return x % 2
data = [1,2,3,4,5,6,7,8,9]
data = filter(is_odd,data)
# object of the "filter" type
data = list(data) # a list again
print(data)
# Output:
# [1, 3, 5, 7, 9]
|
# bubble sort
data = [4,7,1,4,8,9,3,2,5,6]
done = 0
while not done:
done = 1
for n in range(1,len(data)):
# scan left to right
if data[n-1] > data[n]:
# swap two adjacent items
data[n-1], data[n] = data[n],data[n-1]
done = 0 # continue
print(data)
# Output... |
# what is the difference between
# the two given dates?
import datetime
date_from = datetime.date(2019,1,1)
date_to = datetime.date(2019,12,31)
diff = date_to - date_from
print(diff)
days = diff.days # diff in days
print(days)
# Output:
# 364 days, 0:00:00
# 364
|
# one of the simplest programs
# using "async" (python 3.5+)
import asyncio
# methods for working with async
# code
async def f():
# "async" function
print("Hello there!")
asyncio.run(f()) # you need () here
# Output:
# Hello there!
|
# remove newline characters from
# the strings in a list
data = ["alpha\n",
"beta\n",
"gamma\n"]
print(data)
data = list(map(lambda s : s.strip(),data))
# map return an object of the "map" type
print(data)
# Output:
# ['alpha\n', 'beta\n', 'gamma\n']
# ['alpha', 'beta', 'gamma']
|
# catching "Ctrl + C"
c = 0 # counter
try:
while 1: # infinite loop
c += 1
except KeyboardInterrupt:
print(f"The counter is {c} now")
# Input:
# ^C
# Output:
# The counter is 142662630 now
|
# add two numbers from
# command line
a = int(input())
b = int(input())
c = a + b
print(c)
# Input:
# 10
# 20
# Output:
# 30
|
# print the first prime numbers
# below 20
def is_prime(n):
for i in range(2,n):
if not(n % i):
# found divisor,
# thus is not prime
return False
return True # is prime
for n in range(1,20):
if is_prime(n):
print(n)
# Output:
# 1
# 2
# 3
# 5
# 7
# 11
# ... |
# saving a data structure in a file
# in JSON
import json
data = {"alpha" : [3,5,7],
"beta" : [4,6,8]}
with open("code/Data/data.json","w") as f:
json.dump(data,f)
# ...
# using text format now
with open("code/Data/data.json","r") as f:
restored = json.load(f)
print(restored)
# Output:
# {'alp... |
# calling a method of the parent class
class Animal:
def talk(self):
print("I am an animal")
class Cat(Animal):
def talk(self):
print("I am a cat")
# also call Animal.talk:
super(Cat,self).talk()
# ^ child class
# ^ this object
# just remember... |
import random
def BubbleSort(numlist):
lenlist = len(numlist)
# traverse through all elements in the list
for i in range(lenlist):
# last i elements are already in place
for j in range(0,lenlist-i-1):
# traverse through elements from 0 to lenlist - i - 1
# if... |
# what happens when you return
# two values from a function
def f ():
return 10,11
a,b = f()
print(a)
print(b)
# what if you only take one
c = f()
print(c)
# Output:
# 10
# 11
# (10, 11)
|
# find the (only) duplicate
# number in the given list
# of integers
data = [3,4,7,8,1,2,4,9]
# "4" to be found
seen = set()
for x in data:
if x in seen:
# if we already met x
print(x)
break
seen.add(x) # keep collecting
else:
print("No duplicates found")
# Output:
# 4
|
# test if all or any
# items are ture
data = [True,True,False]
if any(data):
print("Some are True")
else:
print("Not a single True")
if all(data):
print("All are True")
else:
print("Not all are True")
# Output:
# Some are True
# Not all are True
|
# count how many times each item
# appears in the list
my_list = ["a","b","a","b","c",
"b","d","b","e","f"]
for item in sorted(set(my_list)):
# set(my_list): each item appears
# only one time
count = my_list.count(item)
print(f"item = {count} times")
# Output:
# item = 2 times
# item = 4 t... |
# a passible implementation
# of a non-recursive factorial
# calculation for positive ints
def factorial(n):
f = 1
for m in range(1,n + 1):
f *= m
return f
print(factorial(5)) # should be 120
# Output:
# 120
|
# increment all elements of a list
data = [10,20,30,40,50,60]
data = [x + 1 for x in data]
# this is a list comprehension
print(data)
Output:
[11, 21, 31, 41, 51, 61]
|
# another way of finding a missing
# number in a list
data = [3,8,1,9,4,10,6,7,2]
s = sum(data) # sum of all items
max = len(data) + 1 # maximum number
s2 = max * (max + 1) / 2 # sum of all
# numbers from 1 to 10 including 10
print(f"{s2 - s} is missing")
# the missing number is actually the
# difference between th... |
# reverse the words in a sentence
text = "Hello, dear World!"
words = text.split() # split by space
words.reverse()
text = " ".join(words)
print(text) # reversed
# Output:
# World! dear Hello,
|
# reading from a text file
for str in open("code/Data/data.txt"):
print(str, end="")
# we should not print the
# newline after each string,
# as "str" already contains it
# Output:
# line 1
# line 2
# line 3
|
# when iterating over
# a dictionary, you get
# the keys of it
data = {"France":"Paris",
"Germany":"Berlin",
"Italy":"Rome"}
for country in data:
print("The capital of " + country + " is " + data[country])
# Output:
# The capital of France is Paris
# The capital of Germany is Berlin
# The capital... |
'''
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
E... |
'''
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Note:
Try to co... |
# Runs in Python 2
'''
Given an underected connected graph with n nodes labeled 1..n. A bridge (cut edge) is defined as an edge which, when removed, makes the graph disconnected (or more precisely, increases the number of connected components in the graph). Equivalently, an edge is a bridge if and only if it is not con... |
def sumOfTwo(a, b, target):
components = dict()
for num1 in a:
components[target - num1] = True
for num2 in b:
if num2 in components.keys():
return True
return False
a = [-5, 0, 0, 32]
b = [9, 1, -2, 10]
result = sumOfTwo(a, b, -8)
print(result)
|
# Solution 1
# O(n * m) Time | O(1) Space
# def distance(x, y):
# x = int(x)
# y = int(y)
# return abs(x - y)
# def smallestDifference(arrayOne, arrayTwo):
# arrayOne.sort()
# arrayTwo.sort()
# closesPairsArray = [float("inf"), float("inf")]
# closestDiff = float("inf")
# for i in range(len(arrayOne)):
#... |
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
headNode = ListNode(1)
secondNode = ListNode(2)
thirdNode = ListNode(3)
headNode.next = secondNode
secondNode.next = thirdNode
# #Traversing the linked list
currentNode = headNode
while currentNode is not None:
print(cur... |
sum = 0
# for i in range(10):
# number = input('Please enter a number: ')
# if int(number) % 2 == 0:
# print('The number is even')
# else:
# print('This number is odd')
number = int(input('Please enter a number: '))
while number is not -1:
if int(number) % 2 == 0:
p... |
mySet1 = set([1, 2, 3, 4, 5])
mySet2 = {1, 2}
mySet2.add(3)
mySet2.add(4)
mySet2.add(5)
mySet2.remove(5)
for element in mySet2:
print(True if element % 2 else False)
mySet = mySet1.union(mySet2)
print(mySet)
mySet = mySet1.intersection(mySet2)
print(mySet) |
s1 = 'waterbottle'
s2 = 'erbottlewat'
s1 = s1 + s1
# waterbottlewaterbottle
output = s1.find(s2)
print(3//2)
# print(output) |
##Files handling order
# myFileHandler = open('countries.txt', 'w')
# myFileHandler.write(str(MyVisitedCountries))
# myFileHandler.read() OR myFileHandler.readLine()
# myFileHandler.close()
MyVisitedCountries = ['SAU', 'ARE', 'JOR', 'EGY']
##Wrtiting to a file
myFileHandler = open('countries.txt', 'w')
# myFileHandle... |
# Do not edit the class below except for the buildHeap,
# siftDown, siftUp, peek, remove, and insert methods.
# Feel free to add new properties and methods to the class.
class MinHeap:
def __init__(self, array):
# Do not edit the line below.
self.heap = self.buildHeap(array)
def buildHeap(self, array):
# Using... |
def dec_htl(func):
def htl(a,b):
if a<b:
a,b=b,a
if func==div and b==0:
return "Not Divisible"
return func(a,b)
return htl
def dec_nonzero(func):
def new_div(a,b):
if b==0:
return "Not Divisible"
else:
return func(a,... |
def countdown (n):
cnt = n + 1 #출력할 지역변수를 만들어줍니다. 하나씩 줄일 것이므로 +1 해주었습니다.
def cntdown():
nonlocal cnt # 클로저의 지역 변수를 변경하기 위해 nonlocal을 사용합니다.
cnt -= 1
return cnt # 이 값이 print(c())에 들어가게 하기 위함입니다.
return cntdown
n = int(input())
c = countdown(n) # cntdown을 리턴하였으므로 c에는 함수 cntd... |
"""
function flattenDict from https://gist.github.com/higarmi/6708779
example: The following JSON document:
{"maps":[{"id1":"blabla","iscategorical1":"0", "perro":[{"dog1": "1", "dog2": "2"}]},{"id2":"blabla","iscategorical2":"0"}],
"masks":{"id":"valore"},
"om_points":"value",
"parameters":{"id":"valore"}}
will have... |
class ExtendedStack(list):
# def append(self, T):
# self.append(T)
# def pop(self):
# self.pop()
def sum(self):
# операция сложения
self.append(self.pop() + self.pop())
# print(self)
def sub(self):
# операция вычитания
self.append(self.pop()-self.pop... |
import numpy as np
def stepVer1(x):#Only with scalar
if(x>0):
return 1
else:
return 0
def stepVer2(x):
y = x>0#bool numpy array
return y.astype(np.int)#Convert to int array
def sigmoid(x):
return 1 / (1+np.exp(-x))
def ReLu(self, x):
return np.maximum(0, x)
def noSoftmax(arr):
... |
import csv
import os
from typing import List, Dict
def listdir_nohidden(path: str):
"""
List not hidden files in directory
Avoid .DS_Store files for Mac
"""
for f in os.listdir(path):
if not f.startswith("."):
yield f
def write_txt_file(path: str, list_to_write: List):
wi... |
############################ Lambda #######################
# A simple one line function. No def or return keywords, they are implicit
# Anonymous Functions
# def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions
# syntax - lambda arguments: expression
# Th... |
#!/usr/bin/env python3
import random
import string
#My random.choices still does not work. So I looked into a work around
def mRNA(seqLength=1000):
"""Generate a random string of fixed length """
bases = 'AUGC'
return ''.join(random.choice(bases) for i in range(seqLength))
#What I think it is ... |
numero = input("Digite um número inteiro: ")
inteiro = int(numero)
dezena = ((inteiro % 100) // 10)
print ("O dígito das dezenas é", dezena)
|
import operator
seats = None
while seats == None:
try:
seats = int(input("Enter number of seats available:"))
if seats <= 0:
print("Number of seats can not be less than 1")
seats = None
elif seats > 10:
print("Number of seats can not be more than 10")
... |
#(8) 튜플
def solution(s):
answer = []
string = s[2:-2].split("},{")
string.sort(key=len)
for i in range(len(string)):
tmp = string[i].split(",")
for j in range(len(tmp)):
if int(tmp[j]) not in answer:
answer.append(int(tmp[j]))
return answer |
def find_start(seq):
"""Finds all of the start codons within a given sequence
and returns the index of the start of the codon"""
#initialize
start_spaces = []
seq = seq.upper()
index = 0
while index < len(seq):
if seq[index] == 'A' and seq[index + 1] == 'T' and seq[index + 2] == 'G... |
class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
sudokuMap = set()
for i in xrange(0,9):
for j in xrange(0,9):
if board[i][j]!='.':
#make sure cur is a string so d... |
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1=set(nums1)
nums2=set(nums2)
numMapping = {}
result = []
for num in nums1:
i... |
# coding: utf-8
# # Implement a program in java or python that contains a .txt file and the 20 statistically significant most common bigrams (by definition the lecture) on the console.
# In[117]:
import os
os.getcwd()
os.chdir("C:\\Users\jiany\Documents\School\Speech & Textmining\Project_Aufgabe")
# In[118]:
... |
#tokenizetxt
def tokenizetxt(fileName, sep):
words = []
if(sep == 1):
with open(fileName, "r") as words_file:
for line in words_file:
t = line.split(',')
word = map(lambda s: s.strip(), t)
words.extend(word) # simply reading text file into a list called words.
if(sep == 0):
with open(fileName,... |
import unittest
from unittest.mock import patch
from text_adventure import TextAdventureEngine
class TextAdventureEngineTestCase(unittest.TestCase):
def test_instance(self):
e = TextAdventureEngine()
self.assertEqual(True, isinstance(e, TextAdventureEngine))
def test_add_room(self):
... |
#!/usr/bin/python3
# Script name: TrafficLightFunction.py
# Uses the red, yellow and green LEDs to simulate a road traffic light
#
# Mark Bradley
# 2019-12-05
# Code divided into functions.
# To exit the code use <ctrl> + c or click the stop button in Thonny
# Import additional libraries.
from gpiozero import LED ... |
"""
Program to calculate optimal wifi node positioning using PSO
Floor plan can be can be read in as a greyscale image file e.g. png.
"""
import sys
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
import numpy as np
from pyswarm import pso
from floorMap import FloorMap
from fitness i... |
"""
This module implements the DATE class, used for transient date storage and manipulation.
It makes various assumptions about how dates will be used,
and insulates the programmer from the full complexity of python date handling.
A DATE class instance wraps around a python datetime, and handles:
- input ('user') da... |
p = int(input())
q = int(input())
oddNumCnt = 0 #奇数的数量
oddNumSum = 0 #奇数和
oddList = [] #奇数列表
for i in range(1, p + 1, 2):
oddNumSum += i
oddNumCnt += 1
oddList.append(i)
if oddNumSum >= q or i >= p:
break
print(oddNumSum)
print(oddNumCnt)
print(max(oddList))
|
# 【问题描述】
#
# 定义一个电话簿,里头设置以下联系人:
#
# 'mayun':'13309283335',
#
# 'zhaolong':'18989227822',
#
# 'zhangmin':'13382398921',
#
# 'Gorge':'19833824743',
#
# 'Jordan':'18807317878',
#
# 'Curry':'15093488129',
#
# 'Wade':'19282937665'
#
# 现在输入人名,查询他的号码。
# 【输入形式】
#
# 人名,是一个字符串。
# 【输出形式】
#
# 电话号码。如果该人不... |
num1=float(input())
num2=float(input())
num3=float(input())
num4=float(input())
num5=float(input())
sum=num5+num4+num3+num2+num1
avg=int(sum/5)
print(avg) |
#Complete the function to return the respective number of the century
#HINT: You may need to import the math module.
import math
def century(year):
return math.ceil(year/100)
#Invoke the function with any given year.
print(century(1801)) |
from problem_utils import *
class HammingDistance:
def minDistance(self, numbers):
input_array = numbers
# The Hamming distance between two numbers is defined as the number of positions in their binary representations at which they differ (leading zeros are used if necessary to make the binary representations ha... |
from problem_utils import *
class TriFibonacci:
def complete(self, A):
input_array = A
# input_array TriFibonacci sequence begins by defining the first three elements input_array[0], input_array[1] and input_array[2].
# The remaining elements are calculated using... |
from problem_utils import *
class FarFromPrimes:
def count(self, A, B):
input_int0 = A
input_int1 = B
# A prime number is an integer greater than 1 that has no positive divisors other than 1 and itself.
# The first prime numbers are 2, 3, 5, 7, 11, 13, 17, ...
# The number N is considered far from primes i... |
from problem_utils import *
class SupermarketDiscount:
def minAmount(self, goods):
input_array = goods
# Three girls are shopping at a supermarket.
# The supermarket is having a sale: "Spend $50 or more in a single transaction and get $10 off."
def spend(x):
##... |
from problem_utils import *
from operator import *
from string import lowercase
class ChangingString:
def distance(self, A, B, K):
input_array1 = A
input_array2 = B
input_int = K
N = len(input_array1)
# You are given two Strings A and B that have the same length and contain ... |
from problem_utils import *
class SkewSymmetric:
def minChanges(self, M):
input_array = M
# A skew symmetric matrix M satisfies M T = - M , where M T denotes the transpose of the matrix M and - M denotes the matrix obtained by multiplying each entry of M by -1.
def skew_symmetric(i,j): M[i,... |
from problem_utils import *
class RandomColoringDiv2:
def getCount(self, maxR, maxG, maxB, startR, startG, startB, d1, d2):
input_int0 = maxR
input_int1 = maxG
input_int2 = maxB
input_int3 = startR
input_int4 = startG
input_int5 = startB
input_int6 = d1
... |
from problem_utils import *
class Pronunciation:
def canPronounce(self, words):
input_array = words
# Peter has problems with pronouncing difficult words.
# In particular he can't pronounce words that contain three or more consecutive consonants (such as "street" or "first").
def ca... |
from problem_utils import *
from operator import *
from string import digits
from numpy import where, array
class InterestingNumber:
def isInteresting(self, x):
input_array = array(x)
# Fox Ciel thinks that the number 41312432 is interesting.
# This is because of... |
from problem_utils import *
class ArrayHash:
def getHash(self, input):
input_array = input
# You will be given a String[] input .
# The value of each character in input is computed as follows: Value = (Alphabet Position) + (Element of input) + (Position in Element) All positions are 0-based.
# 'A' has alphab... |
from problem_utils import *
class BlockTower:
def getTallest(self, blockHeights):
input_array = blockHeights
N = len(input_array)
# Josh loves playing with blocks.
# Currently, he has N blocks, labeled 0 through N-1.
# The heights of all ... |
from problem_utils import *
class InequalityChecker:
def getDifferences(self, n):
input_int = n
# Using mathematical induction it is possible to prove the following inequality when n >1: s = 13 + 23 + ... + (n-1)3 < n4/4 < 13 + 23 + ... + n3 = S Given n return (S+s)/2 - n 4 /4 as a int[] with 2 elements.
# Ele... |
from problem_utils import *
class FilipTheFrog:
def countReachableIslands(self, positions, L):
input_array = positions
input_int = L
# Filip the Frog lives on a number line.
# There are islands at some points on the number line.
# You are given the positions of these islands in the int[] positions .
# Fi... |
from problem_utils import *
class FoxAndGame:
def countStars(self, result):
input_array = result
# Fox Ciel is playing the popular game 'Cut the Rope' on her smartphone.
# The game has multiple stages, and for each stage the player can gain between 0 and 3 stars, inclusive.
# You are given a String[] result ... |
from problem_utils import *
from operator import *
from string import lowercase
class DifferentStrings:
def minimize(self, A, B):
input_array1 = A
input_array2 = B
N = min(len(input_array1),len(input_array2))
elements = lowercase
# If X and Y are two Strings of equal length N, then the difference between t... |
from problem_utils import *
from string import lowercase
class CorruptedMessage:
def reconstructMessage(self, s, k):
input_array = s
input_int = k
N = len(input_array)
''' Your friend just sent you a message.'''
# The message consisted of one or more copies of the... |
from problem_utils import *
from operator import *
class IdentifyingWood:
def check(self, s, t):
input_array0 = s
input_array1 = t
# We call a pair of Strings (input_array0, input_array1) "wood" if input_array1 is contained in input_array0 as a subsequen... |
from problem_utils import *
from operator import *
import numpy
class Elections:
def visit(self, likelihoods):
input_array = likelihoods
N = len(input_array)
# There are two candidates campaigning to be president of a country.
# From newspaper polls, it is clear what percentages of ... |
from problem_utils import *
from operator import *
class HammingDistance:
def minDistance(self, numbers):
input_array = numbers
N = len(input_array[0])
# The Hamming distance between two input_array is defined as the number of positions in their binary r... |
class FingerCounting:
def maxNumber(self, weakFinger, maxCount):
input_int1 = weakFinger
input_int2 = maxCount
# Your little son is counting numbers with his left hand.
# Starting with his thumb and going toward his pinky, he counts each finger in order.
# After counting h... |
from problem_utils import *
from operator import *
class LCMRange:
def lcm(self, first, last):
input_int0 = first
input_int1 = last
inf = 1000
# The least common multiple of a group of integers is the smallest number that can be evenly divided by... |
from problem_utils import *
class RugSizes:
def rugCount(self, area):
input_int = area
ways = list(combinations_with_replacement(range(inclusive(area)), 2))
# Rugs come in various sizes.
# In fact, we can find a rug with any integer width and length, except that no rugs ha... |
# A partir del ejercicio anterior, vamos a suponer que cada número es una nota, y lo que queremos es obtener la nota final.
# El problema es que cada nota tiene un valor porcentual:
# La primera nota vale un 15% del total.
# La segunda nota vale un 35% del total.
# La tercera nota vale un 50% del total.
nota_1 = 10
n... |
import turtle
import time
import random
delay = 0.1
# ate rate
ate = 0
topaterate = 0
# play field
window = turtle.Screen()
window.title("Pysnakegame by @shohan")
window.bgcolor("blue")
window.setup(width=650, height=650)
window.tracer(0)
# lets make the snake
head = turtle.Turtle()
head.speed(0)... |
def collatz(number):
if number % 2 == 0:
return number//2
elif number % 2 ==1 :
return 3*number+1
try:
print("Enter number:")
input_name = int(input())
while True:
input_name=collatz(input_name)
print(input_name)
if input_name ==1:
br... |
print("*****************************List Ends**************************************")
my_list = [5, 10, 15, 20, 25]
def list_end():
return [my_list[0], my_list[-1]]
new_list = list_end()
print(new_list)
|
# Without using set
my_list = [1, 2, 3, 4, 3, 2, 1]
def remove_dup1():
new_list = []
for i in my_list:
if i not in new_list:
new_list.append(i)
return new_list
print(remove_dup1())
# By using set
def remove_dup2(x):
return list(set(x))
print(remove_dup2(my_list))
|
# Masukkan angka
angka = int(input("Masukkan angka "))
# Cek angka 1
if angka % 2 == 0 and angka != 0:
print(angka, "angka genap")
elif angka % 2 != 0:
print(angka, "angka ganjil")
else:
print(angka, "bukan genap maupun ganijl")
# Cek angka 2
if angka < 0:
print(angka, "angka negatif")
eli... |
''' script to run yardsale data through the google api to
get the longitude and latitude
'''
import Util
from keys import key
# load the data as JSON lines
# get lng/lat for each post's address
# save as new JSON lines so compass can access
def AttachGeoData():
infilename = 'server/gatherer/post_data/yardsale... |
x = 10
y = 5
x = x ^ y;
y = x ^ y;
x = x ^ y;
print ("After Swapping: x = ",x ," y =", y)
|
a=int(input("Enter a number"))
l=[]
count=0
for i in range(0,a):
b=int(input("Enter number"))
l.append(b)
count+=1
if(count%2==0):
print("yes")
els:
print("no")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.