text stringlengths 37 1.41M |
|---|
num1=int(input("value"))
num2=int(input("value"))
num3=int(input("value"))
if ((num1>num2)&(num1>num3)):
if(num2>num3):
print(num1,",",num2,",",num3)
else:
print(num1, ",", num3, ",", num2)
elif((num2>num1)&(num2>num3)):
if(num1>num3):
print(num2, ",... |
#identifiers? #for comments
#simply a name is called identifiers
#variable name , function name , class name
#variables are used fo representing a memory location
#num1=2 #variable is num1
#1num=10 # not valid reason is variable name always start with alphabet
#nummmmmmmm=12 #thre is no length lim... |
employees=[
[1001,"ajay","qa",1981,2003],
[1002,"vijay","developer",1992,2008],
[1003,"arun","ba",1989,2010],
[1004,"amal","developer",2009,2014],
[1005,"vimal","developer",1987,1989]
]
#print all employee desigination
for emp in employees:
print(emp[2])
print()
#print all employees whose desi... |
#to perform a specific task
#input()
#print()
#def mul(num1,num2):
#res=num1*num2
#print (res)
#def div(num1,num2):
#res=num1/num2
#print(res)
#mul(10,20)
#div(20,10)
#function wit arguments and return value:
#def add(num1,num2):
#res=num1+num2
#return res
#data=add(10,20)
#print(dat... |
lst=[-2,-1,0,2,3,4]#find least +ve missing integer
#print(1 in lst) #check for 1 in lst or not
cnt=1
for i in range(0,len(lst)):
if cnt in lst:
cnt+=1
else:
print(cnt,"is missing least +ve integer")
break |
num=input("enter the value")
i=1
sum=0
while(i<=int(num)):
data=num*i
sum=sum+int(data)
i=i+1
print(sum) |
limit=int(input("enter value"))
sum=0
i=1
while(i<=limit):
sum=sum+i
i=i+1
print("sum is ", sum) |
# -*- coding: utf-8 -*-
# 'author':'zlw'
"""
队列是一种操作被约束的线性表,队列可以使用数组或者链表实现。
队列的约束操作是:
在队列的一端追加元素,而在另一端弹出元素,满足FIFO的顺序特性。
"""
# 定义链表元素
class Element(object):
def __init__(self, value):
self.value = value
self.next_element = None
# 基本的队列实现
class BasicQueue(object):
element_class = Element... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# 'author':'zlw'
"""策略模块
此模块定义了各种策略类。
"""
class BasePolicy(object):
pass
# 价格策略基类
class BasePricePolicy(BasePolicy):
pass
# 普通价格策略类
class CommonPricePolicy(BasePricePolicy):
name = 'common' # 正常收银
def calculate(self, price):
print('检测价格,返回原... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# 'author':'zlw'
"""工厂模块
为每一个业务类编写一个工厂类以提供:实例化控制、封装。
工厂类与业务类为一对一映射关系。
"""
from abc import ABCMeta, abstractmethod
from src.operators import (
Add,
Sub,
Multi,
Division,
)
class AbstractFactory(object, metaclass=ABCMeta):
"""抽象工厂类"""
@abs... |
"""
A simple selenium test example written by python
"""
import unittest
import sys
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
class TestTemplate(unittest.TestCase):
"""Include test cases on a given url"""
def setUp(self):
"""Start web driver"""
... |
class Node:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def getNextNode(self, node: Node) -> int:
if node == None or node.next == None:
return None
return node.next
def getNodeVal(self, node: Node) -> int:
if node == None or node.val == Non... |
import math
import numpy as np
import matplotlib.pyplot as plt
#fun1 is y = 9.81 -0.0025*x**2
#fun2 is y = -x
def rungeKuttaMethod(dim1,dim2,step,fun1,fun2):
time = [0]
dim1List = [dim1]
dim2List = [dim2]
dim2_current = dim2
i = 0
while dim2_current > 0:
#F1
vF1 = fun1(... |
import numpy as np
'''
1. Linear algebraic equations can arise in the solution
of differential equations. For example, the following heat
equation describes the equilibrium temperature
T = T(x)(oC)
at a point x (in meters m) along a long thin rod,
d2T/dx2 = h′(T − Ta), (1)
where Ta = 10oC... |
def Secant(function,xLower, xUpper, es, imax):
# Secant method to finds a root of a funtion.
# xLower: lower bound guess.
# xUpper: upper bound guess.
# es: error threshold.
# imax: max iterations threshold.
iter =0
xr = xLower
ea = es
xr_old = xr
while (ea >= es) and (iter < im... |
import requests
from bs4 import BeautifulSoup
import pandas as pd
"""Gets page request and stores the content"""
def getPageRequest():
newYork = "https://forecast.weather.gov/MapClick.php?lat=40.7146&lon=-74.0071"
meadville = "https://forecast.weather.gov/MapClick.php?lat=41.63648000000006&lon=-80.151429999... |
# for loop allows us to do something over
# and over again
# structure of for loop
# for item in collection:
# print(item)
# print every letter in a word
for char in "hello world":
print(char)
# range: used to generate a range
# of numbers to help with looping
# in for loops. range will start
# its count at 0... |
def main():
# some simple data types that we have in Python
# boolean: True or False
isGameOver = False
print("isGameOver is of type")
print(type(isGameOver))
print()
# integer: integers are whole numbers
myAge = 23
print("myAge is of type")
print(type(myAge))
print()
... |
# some extra list methods
# index: returns the index of the specified
# item in the list
#
# you can also pass in a starting index
# to start the search from
# index(item, start_index)
#
# you can also pass in a ending index to
# identify a stop point for the index search
# index(item, start_index, end_index)
numbers... |
s=input("Enter String")
if s>='a' and s<='z':
print(s.upper())
|
'''
Roy wanted to increase his typing speed for programming contests. His friend suggested that he type the sentence "The quick brown fox jumps over the lazy dog" repeatedly. This sentence is known as a pangram because it contains every letter of the alphabet.
After typing the sentence several times, Roy became bored ... |
# Sample code to read input and write output:
'''
NAME = input() # Read input from STDIN
print("Hello " + NAME) # Write output to STDOUT
'''
# Warning: Printing unwanted or ill-formatted
# data to output will cause the test cases to fail
# Write your code here
def problem3():
line =... |
'''
Problem: Given the root node of a binary tree, return the length of the longest path in the tree (node to node)
ex.
10
1 20
0 2
Ex.
10
/ \
4 11
/ \
3 5
/ \
2 9
/ /
1 7
Lo... |
'''
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-... |
'''
Given a string s, the power of the string is the maximum length of a non-empty substring that contains only one unique character.
Return the power of the string.
Example 1:
Input: s = "leetcode"
Output: 2
Explanation: The substring "ee" is of length 2 with the character 'e' only.
Example 2:
Input: s = "abbc... |
'''
Given a string, sort it in decreasing order based on the frequency of characters.
Example 1:
Input:
"tree"
Output:
"eert"
Explanation:
'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
Example 2:
Input:
"cccaaa"
Output:
... |
'''
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time.
Each transformed word must exist in the word list.
Note:
Return 0 if there is no such transformati... |
'''
We are given an array asteroids of integers representing asteroids in a row.
For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
Find out the state of the asteroids after all colli... |
#a child is running up a staircase with n steps and can hop either 1, 2 or 3 steps at a time. implement a method to count how many possible ways the child can run up the stairs
'''
Example: 1
1
Ex: 2
1, 1
2
ex. 3
1, 1, 1
1, 2
2, 1
3
--
1, 1, 1, 1, 1
1, 2, 1, 1
'''
#total = 0
def numPossibleWays(n):
if (... |
'''
You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins.
Given n, find the total number of full staircase rows that can be formed.
n is a non-negative integer and fits within the range of a 32-bit signed integer.
Example 1:
n = 5
The coins can form... |
cost = 2
received = int(input("Insert money: "))
if received < cost:
print("Insert more money")
else:
change = received - cost
if change > 0:
print(f"Change given {change}")
else:
print("No change needed")
|
import math
import numpy as np
def calculate_fuel(amount):
return math.floor(amount / 3) -2
sum = 0
file = open("input.txt", "r")
for line in file:
fuel = calculate_fuel(int(line))
sum = sum + fuel
print ("first answer ",sum)
fuels = []
file = open("input.txt", "r")
for line in file:
fuel = calcul... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: qjk
class Solution:
def ReverseSentence(self, s):
# write code here
if s.strip() == "":
return s
result = s.split()
str = ''
for item in result[::-1]:
str += " " + item
return str.lstrip(... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: qjk
class Solution:
def __init__(self):
self.a = []
def Insert(self, num):
# write code here
self.a.append(num)
def GetMedian(self):
# write code here
self.a.sort()
if len(self.a)%2 == 1:
r... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: qjk
# class TreeLinkNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
def GetNext(self, pNode):
# write code here
if not pNode:
... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: qjk
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def Convert(self, pRootOfTree):
# write code here
if not pRootOfTree:
return None
... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: qjk
class Solution:
def VerifySquenceOfBST(self, sequence):
# write code here
if len(sequence) == 0:
return False
root = sequence[-1]
# 寻找二叉树小于根节点的数
i = 0
for item in sequence[:-1]:
if ... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: qjk
'''
前提是一次只能跳1阶或者2阶的跳法
a.如果两种跳法,一阶或者两阶,那么假定第一次跳的是一阶,那么剩下的就是n-1阶,跳法是f(n-1)
b.假定第一次跳的是2阶,那么剩下的是n-2阶,跳法是f(n-2)
c.由a and b假设可以得出总跳法f(n)=f(n-1)+f(n-2)
d f(1) = 1 f(2)=2
'''
class Solution:
def jumpFloor(self, number):
# write code here
if number... |
totalSum = 0
f = open("day12input.txt", "r")
textDump = f.readline()
value = ""
for i in range(len(textDump)):
if(textDump[i].isdigit() or (textDump[i] == "-"and len(value)==0)):
value += textDump[i]
elif(len(value) != 0):
totalSum += int(value)
value = ""
print(totalSum) |
import re
circuit = {}
circuit['1'] = 1
circuit['b'] = 3176
operations = []
f = open('day7input.txt', 'r')
def assignFunc (operand1, operand2, target):
signal1 = circuit.get(operand1)
signal2 = None
if (signal1 == None):
return False
circuit[target] = signal1
return True
def notFunc (operand1, operand2, targ... |
#Given a range(l,r), print the maximum value of XOR obtained for a combination of 2 values that are present within the range
import itertools
import operator
def maximizingXor(l, r):
l1=[]
for i in range(l,r+1):
l1.append(i)
l2=list(itertools.combinations(l1,2))
m=0
for i in ra... |
def substractProductAndSum(n):
n = str(n)
length = len(n)
product = 1
sumOfNumbers = 0
numberToConvert = ""
for i in range (0, length):
numberToConvert = n[i]
numberToConvert = int(numberToConvert)
product *= numberToConvert
sumOfNumbers += numberToConvert
... |
def threeSum(self, nums: List[int]) -> List[List[int]]:
# returns empty array if not enough elements
n = len(nums)
if n < 3:
return []
# sort the nums list
nums.sort()
# set of nums for faster lookup
numSet = {integer: i for i, intege... |
# temperature transfer
Temp = input("¶ֵ(F/C):")
# ϶
if Temp[-1] in ['C','c']:
F = 1.8 * eval(Temp[0:-1]) + 32
print("{:.2f}".format(F))
# 뻪϶
elif Temp[-1] in ['F','f']:
C = (eval(Temp[0:-1]) - 32) / 1.8
print("{:.2f}".format(C))
else:
print("Error!!")
# TemStr = input("input temp(F/C):")
# if TemStr[-1] in... |
# 倒背如流
st = input("请输入一段字符:")
i = len(st) - 1
while i >= 0:
print(st[i], end = "")
i = i - 1
|
# body mass index v.01
height, weight = eval(input("请输入身高和体重[逗号分隔]:"))
bmi = weight / pow(height, 2)
print("bmi的值为:{:.2f}".format(bmi))
# 判断 18.5 25 30
who = ""
if bmi < 18.5:
who = "偏瘦"
elif 18.5 <= bmi < 25:
who = "标准"
elif 25 <= bmi < 30:
who = "偏胖"
else:
who = "肥胖"
print("国际标准为:{}... |
#!/usr/bin/python3
print('+---------------------+')
print('| Best Friend Maker |')
print('| By Ian Pierce |')
print('+---------------------+')
print('')
name = input('What is your name? ')
print('')
num = 42
print("I'm thinking of a number between 0 and 100. Can you guess it?")
guess = input("What is your gu... |
import re
text = "Ten 10, Twenty 20, Thirty 30"
result = re.split("\D+", text)
for element in result:
print(element) |
import re
def capital_words_spaces(str1):
return re.sub(r"(\w)([A-Z])", r"\1 \2", str1)
print(capital_words_spaces("Python"))
print(capital_words_spaces("PythonExercises"))
print(capital_words_spaces("PythonExercisesPracticeSolution"))
|
import re
text1 = ' Python Exercises '
print("Original string:",text1)
print("Without extra spaces:",re.sub(r'\s+', '',text1)) |
from card import Card
class PyramidBoard():
"""
Class for representing the pyramid structure.
Class describes the structure of the pyramid and its functional:
Create pyramid.
Show pyramid.
Checking the presence, obtaining, deleting cards.
"""
def __init__(self):
... |
T = int(input())
for t in range(1,T+1):
word = input()
new_word = ''
for i in range(-1,-len(word)-1,-1):
new_word += word[i]
if word == new_word:
print(f'#{t} 1')
else :
print(f'#{t} 0')
|
import sys
sys.stdin = open('s_input.txt')
# nC2를 통하여 부분집합을 구한다.
# 곱한다
# 단조증가를 확인한다
def bubble_sort(number):
for i in range(len(number)-1, 0, -1):
for j in range(i):
if number[j] > number[j+1]:
number[j], number[j+1] = number[j+1], number[j]
return number
def plus_number(... |
def check(times):
if times[2] < times[0]:
return times[0] - times[2]
elif times[0] <= times[2] <= times[1]:
return 0
else:
return -1
T = int(input())
for t in range(1, T+1):
times = list(map(int, input().split()))
print('#{} {}'.format(t, check(times)))
|
import sys
sys.stdin = open('sample_input.txt')
def check(number, special):
while number:
if number % 10 == special:
return True
number = number // 10
return False
def special_number(numb1, numb2, special):
answer = 0
numbers = []
for number in range(numb1, numb2+1):
... |
N = int(input())
for number in range(1, N+1):
clap = 0
answer = str(number)
for idx in ['3','6','9']:
clap += answer.count(idx)
if clap == 0 :
answer = str(number)
else :
answer = '-' * clap
print(answer, end = ' ')
|
import os
import string
def isValidDirectory(argument, path):
'''Checks whether the inputted directory exists or not.'''
if not os.path.isdir(path):
raise ValueError(f'Folder path for {argument} does not exist.')
def isIntOverZero(argument, someVariable):
'''Checks if variable is of type int and... |
import random
from art import logo
from replit import clear
print(logo)
n=0
from game_data import data
length= len(data)
item2= random.randint(0, length-1)
loop=True
while loop:
item1=item2
item2= random.randint(0, length-1)
if item1==item2:
continue
first=data[item1]
name= first["name"]
p... |
def fibonacci(n):
result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b, a+b
return result
sequence = fibonacci(4000000)
seq2 = []
for e in sequence:
if e % 2 == 0:
seq2.append(e)
print sum(seq2)
print sequence
print seq2
|
from itertools import combinations
from random import randint
class Lotto:
"""
A Lotto class based on Steven Skiena's Algorithm Design Manual (Chapter 1)
"""
def __init__(self, n=15, k=6, j=4, l=3):
self._n = n
self._k = k # slots on ticket
self._j = j # number of psychically-pr... |
# Example of polynomial regression on synthetic dataset
import numpy as np
import pandas as pd
import seaborn as sn
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.linear_model import Ridge
from sklearn.preprocessing i... |
# Binary logistic regression with fruits dataset (apple vs others)
import numpy as np
import pandas as pd
import seaborn as sn
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
# prepare fruits dataset using only 2 features
fruits... |
a= int(input())
b= int(input())
c= int(input())
if(a==1 and c==1):
print 2+b
elif(a==1):
print (a+b)*c
elif(b==1):
print max((a+b)*c,a*(b+c))
elif(c==1):
print a*(b+c)
else:
print a*b*c |
# 1. Написати скрипт, який з двох введених чисел визначить, яке з них більше,
# а яке менше.
def int_is_bigg_or_small(a: int, b: int):
return f'{a} is bigger than {b}' if a > b else f'{a} is smaller than {b}'
if __name__ == '__main__':
assert int_is_bigg_or_small(2, 4) == '2 is smaller than 4'
assert int_... |
# try:
# a = int(input('press int: '))
# if a % 2 == 0 :
# print(f'{a} it int is odd')
# elif a % 2 != 0:
# print(f'{a} is not even')
# except ValueError:
# print('is type uncorrected, print pls integer')
# 2. Напишіть програму, яка пропонує користувачу ввести свій вік, після чого ви... |
# Consider an array of sheep where some sheep may be missing from their place.
# We need a function that counts the number of sheep present in the array (true means present).
array1 = [True, True, True, False,
True, True, True, True,
True, False, True, False,
True, False, False, True,
... |
# We will here attempt to predict continuous values for an attribute using regression techniques such as ordinary least squares regression model
from helper import *
from sklearn.model_selection import train_test_split
import sklearn.linear_model as lm
import sklearn.neural_network as nn
import numpy as np
import mat... |
#
# Gradient descent with 1D data i.e. 2 features
#
import numpy as np
import matplotlib.pyplot as plt
# Load data file
filenameIn = 'OneFeature.csv'
data = np.loadtxt(filenameIn, delimiter=',')
print('Shape of data matrix', data.shape)
# Extract x and y vectors from data
x = data[:,0]
y = data[:,1]
#... |
''' Antonio Pelayo April 2, 2020
Problem: 189 Rotate Array
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]
rotat... |
''' Antonio Pelayo March 8, 2020
Problem 7. Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within
the... |
''' Antonio Pelayo March 15, 2020
Problem: Contains Duplicate
Difficulty: Easy
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the
array, and it should return false if every element is distinct.
Example 1:
Input: [1,2,3,1... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys, os,re,time
def countWords(texto):
tiempo=time.time()
palabras=0
for linea in texto.splitlines():
linea= re.sub(r'[-,;:?!.¿¡\'\(\)\[\]\"|*+-_<>#@&^%$]'," ",linea)
for p in linea.split():
palabras+=1
print ("\nCountWords: Palabras obtenidas: "+str(pal... |
# %%
# Question 1:
# Traverse a nested list and print all elements.
names = [
"Adam",
[
"Bob",
[
"Chet",
"Cat",
],
"Barb",
"Bert",
],
"Alex",
["Bea", "Bill"],
"Ann",
]
# %%
# Question 2:
# FInd the sum of all the elements of a nest... |
# WAF to generate a random alphabetical string and alphabetical string of a
# fixed length.
import random
import string
LETTERS = string.ascii_letters + string.digits
def password_generator(length):
my_string = ""
for _ in range(0, length):
n = random.randrange(0, len(LETTERS))
nth_char = LE... |
import random
from colorama import Fore, init
import utils
init(autoreset=True)
words = utils.data
to_guess = utils.Word(random.choice(words))
spaces = utils.Guess(to_guess)
number_of_guesses = 0
total_guesses = int(input('How many guesses would you like to make? '))
letters_guessed = set()
while True:
prin... |
# coding=utf-8
'''
Problem 25 - 1000-digit Fibonacci Number
The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is t... |
'''
Problem 41 - Pandigital Prime
We shall say that an n-digit number is pandigital if it makes use of all the
digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is
also prime.
What is the largest n-digit pandigital prime that exists?
'''
from lib.helpers.runtime import print_answer_and_elapse... |
# coding=utf-8
'''
Problem 46 - Goldbach's Other Conjecture
It was proposed by Christian Goldbach that every odd composite number can be
written as the sum of a prime and twice a square.
9 = 7 + 2×1**2
15 = 7 + 2×2**2
21 = 3 + 2×3**2
25 = 7 + 2×3**2
27 = 19 + 2×2**2
33 = 31 + 2×1**2
It turns out that the conjecture ... |
'''
Problem 34 - Digit Factorials
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial of
their digits.
Note: as 1! = 1 and 2! = 2 are not sums they are not included.
'''
from math import factorial
from lib.helpers.runtime import prin... |
'''
Problem 3 - Largest Prime Factor
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
'''
from functools import partial
from lib.helpers.runtime import print_answer_and_elapsed_time
from lib.helpers.numbers import prime_divisors
def largest_prime_factor(... |
'''
Problem 44 - Pentagon Numbers
Pentagonal numbers are generated by the formula, P_n=n(3n−1)/2. The first ten
pentagonal numbers are:
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
It can be seen that P_4 + P_7 = 22 + 70 = 92 = P_8. However, their difference,
70 − 22 = 48, is not pentagonal.
Find the pair of pentago... |
'''
Problem 54 - Poker Hands
In the card game poker, a hand consists of five cards and are ranked, from
lowest to highest, in the following way:
High Card: Highest value card.
One Pair: Two cards of the same value.
Two Pairs: Two different pairs.
Three of a Kind: Three cards of the same value.
Straight: All cards are... |
def is_palindrome(string):
if (len(string) < 2):
return True
if (not string.endswith(string[0])):
return False
return is_palindrome(string[1:-1])
|
# Exercise 6, Learn Python the Hard Way
# define a variable
types_of_people = 10
# define var x with a formatted string
x = f"There are {types_of_people} types of people."
# define variable
binary = "binary"
# define variable
do_not = "don't"
# define var y with formatted string
y = f"Those who know {binary} and thos... |
"""
Class representing the pen
"""
from vectdraw.draw.colour import Colour
class Pen(object):
__kDefaultColour = Colour()
# determines the position of pen. False is Up, True is Down
__isDown = False
# Current colour of the pen (red, green, blue, alpha)
__colour = __kDefaultColour
def ChangeCo... |
"""
Class for rgba colour representation
"""
class Colour(object):
red = 0
green = 0
blue = 0
alpha = 255
def __init__(self, rgba=None):
"""
Returns a colour instance. If nothing is passsed, the default
is 0,0, 0, 255 for red, green, blue and alpha respectively
:param rgba: ... |
# =================================
# Simple bank Account Class
# =================================
# This is the Bank Account Class (template for bank account instances)
class BankAccount:
""" Creating simple bank account with balance """
def __init__(self, name, balance):
self.name = name
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Example embedding look-up for explaining how torch.index_select and torch.view work
Inspired by assignment 3 of Stanford's CS224n class on NLP, spring 2020
For explanations, see dstei.github.io/pytorch-index_select-example
"""
import torch
torch.manual_seed(0)
batch_... |
"""
Домашнее задание №1
Исключения: KeyboardInterrupt
* Перепишите функцию ask_user() из задания while2, чтобы она
перехватывала KeyboardInterrupt, писала пользователю "Пока!"
и завершала работу при помощи оператора break
"""
def ask_user():
"""
Замените pass на ваш код
"""
q_and_a = {'Ho... |
# Homework #2
# https://github.com/SunJieMing/python-minicamp-homework-2
# Special thanks to @Taic who help me to understand the last part of the extra credit.
# -------------------------------------
# from flask import Flask
from flask import Flask, render_template, jsonify
app = Flask(__name__)
# -----... |
# Find possible ways in a Dice Game
# using efficient approach instead of Decision Tree
import sys
def find_possible_ways_dice_game(faces, distance):
pre_values = [0 for x in range(faces)]
cur_values = [0 for x in range(faces)]
for i in range(1, distance+1):
if i <= faces:
if i ==... |
adj = [
[4, 2, 1], # 0
[0, 2], # 1
[0, 1, 3], # 2
[2], # 3
[0], # 4
[], # 5
]
def dfs(node, end, visited):
if node == end:
return True
for neigh in adj[node]:
if not visited[neigh]:
visited[neigh] = True
if dfs(neigh, end, vi... |
# coding: utf-8
linhas = ['ana', 'beatriz', 'clara']
linhas
# lista de strings >>> string
' '.join(linhas)
'--'.join(linhas)
s = ''.join(linhas)
s
s = ' '.join(linhas)
# string >>> lista de strings
s.split()
s = '--'.join(linhas)
s
s.split()
s.split('--')
s = '1 2 3 4'
l = s.split()
l
[1, 2, 3, 4]
nums = []
l
for ... |
import random
array = input().split()
array = [int(num) for num in array]
def selection_sort(array):
N = len(array)
start = 0
while start < N:
index = start
min_index = start
while index < N: # [start, ..., N-1]
if array[index] < array[min_index]:
m... |
import time
from collections import deque
N = int(input())
lista = [0] * N # 10k
queue = deque(lista)
start = time.time()
while len(queue) > 0: # while lista:
queue.pop()
end = time.time()
print('Tempo Necessário tirando do final: ', end-start)
lista = [0] * N # 10k
queue = deque(lista)
start = time.time()
wh... |
# dictionary to store data
nick_names ={
"jason" : "jay",
"kenneth" : "ken",
"Jacob" : "Coby",
"William" : "Bill",
"Alexander": "Alex",
}
print(nick_names.get("Alexander", "key not found")) #the key with get function
|
import numpy as np
from random import shuffle
def softmax_loss_naive(W, X, y, reg):
"""
Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing we... |
from tkinter import*
import tkinter.messagebox
import stdDatabase
class Student:
def __init__(self,root):
self.root = root
self.root.title("Students Database Management System")
self.root.geometry("1350x750+0+0")
self.root.config(bg="dark orange")
StdID = Str... |
my_pets = ['lily', 'moss', 'tabbie']
print('Enter a pet name:')
name = input()
if name not in my_pets:
print('I do not have a pet named ' + name)
else:
print(name + ' is my pet.') |
def spam():
eggs = "spam local"
print(eggs) #prints spam local
def bacon():
eggs = "bacon local"
print(eggs) #prints bacon local
spam()
print(eggs) #prints bacon local
eggs = "global"
bacon() #overwrites with parameters within the called function
print(eggs) #prints "global"
#set to global
#o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.