text stringlengths 37 1.41M |
|---|
"""
类 与对象(实例)
类:模板定义属性和方法的封装
实例:具体的类对象 ,类的表现
1实例属性会根据实例不同而不同,类属性由类决定
2实例属性通常在构造赋值
3类属性(类变量)属于类 , 实例属性属于实例
实例确定,实例属性确定
实例可以调用类属性 ,类不可以调用实例属性
"""
class Good():
name = 'tea'
def __init__(self, _addr):
self.addr = _addr
g1 = Good("fujian")
g2 = Good("guangdong")
print(g1.addr,g2.addr,g1.name,g2.name)
... |
"""
引用计数
"""
from sys import getrefcount
list1 = [x for x in range(10)]
list2 = [x for x in range(10, 20)]
print(list1)
print(list2)
print("=========================================")
print(getrefcount(list1))
print(getrefcount(list2))
print("=========================================")
list1.append(list2)
prin... |
# -*- coding: utf8 -*-
'''
Программа принимает действительное положительное число x и целое отрицательное число y.
Выполните возведение числа x в степень y. Задание реализуйте в виде функции my_func(x, y).
При решении задания нужно обойтись без встроенной функции возведения числа в степень.
Подсказка: попробуйте решить... |
# -*- coding: utf8 -*-
'''
Создать (программно) текстовый файл, записать в него программно набор чисел,
разделённых пробелами. Программа должна подсчитывать сумму чисел в файле и выводить
её на экран.
'''
# with open('Digits_kit.txt', 'w+', encoding='utf-8') as dig_kit:
# print(' '.join([str(i) for i in range(1,11... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 12 15:28:02 2019
@author: Chengcheng Ding
"""
from tkinter import *
from tkinter import messagebox
from random import *
class App(Frame):
def __init__(self,master = None):
Frame.__init__(self, master)
self.pack()
self.cre... |
# Python program to explain os.getenv() method
# importing os module
import os
import sys
key = 'HOME'
value = os.getenv(key)
print("Value of 'HOME' environment variable :", value)
key = 'JAVA_HOME'
value = os.getenv(key)
print("Value of 'JAVA_HOME' environment variable :", value)
key="IN_MPI"
value = os.getenv(key... |
a = 3
a = a + 7
print(a)
a += 5 # a = a +5
print(a)
a -=5
print(a)
a *=2
print(a)
a /=4
print(a)
a %= 4
print(a)
a += 1
print(a)
a **=10
print(a) |
a = {1, 2, 3}
print(type(a))
b = set('angelo mutti')
print(b)
print('a' in b, 'sousa' not in b)
# o que vale são os valores que compõem o conjunto, verdadeiro
print({1, 2, 3} == {3, 2, 1, 3, 2})
c1 = {1, 2}
c2 = {2, 3}
print(c1.union(c2))
print(c1.intersection(c2))
c1.update(c2)
print(c1)
c3 = {1, 2, 3, 4, 5, 6}
c4... |
trabalho_terca = True
trabalho_quinta = False
'''
os 2 = tv de 50
apenas 1 = tv de 32
'''
tv_50 = trabalho_quinta and trabalho_terca
sorvete = trabalho_terca or trabalho_quinta
tv_32 = trabalho_terca != trabalho_quinta
mais_saudavel = not sorvete
print("tv50={} tv32={} sorvete={} mais_saudavel={}" .format(
tv_50... |
salario = 3450.45
despesas = 2456.2
print(despesas / salario * 100) #esta é porcentagem do salário que vai nas despesas
#metodo do professor
percentual_comprometido = despesas / salario * 100
print(percentual_comprometido) |
# 표준 입력으로 삼각형의 높이가 입력됩니다.
# 입력된 높이만큼 산 모양으로 별을 출력하는 프로그램을 만드세요.
# (input에서 안내 문자열은 출력하지 않아야 합니다).
# 이때 출력 결과는 예제와 정확히 일치해야 합니다.
# 모양이 같더라도 공백이나 빈 줄이 더 들어가면 틀린 것으로 처리됩니다.
n = int(input())
index = 1
for i in range(n):
for j in range(n):
if j > i:
print(' ', end = '')
if i > 0:
index... |
# 회문 판별하기
# 회문은 순서를 거꾸로 읽어도 제대로 읽은 것과 같은 단어와 문장
word = input('단어를 입력하세요.')
is_palindrome = True
for i in range(len(word) // 2):
if word[i] != word[-1 - i]:
is_palindrome = False
break
print(is_palindrome) |
if True:
print('참')
else:
print('거짓') # True는 참
if False:
print('참')
else:
print('거짓') # False는 거짓
if None:
print('참')
else:
print('거짓') # None은 거짓
if 0:
print('참')
else:
print('거짓') # 0은 거짓
if 1:
print('참')
else:
print('거짓') # 1은 참
# 숫자는 정수, 실수 관계없이 0은 거짓이고 0이 아닌 수는 참이다.
# ... |
print(1, 2, 3)
print(1, 2, 3, sep='\n')
# print의 sep에 개행 문자(\n) 이라는 특별한 문자를 지정하면 값을 여러 줄로 출력할 수 있다.
print('1\n2\n3')
# 결과가 같음
# 제어 문자
# 제어 문자는 화면에 출력되지는 않지만 출력 결과를 제어한다고 해서 제어 문자라 부른다.
# 또한, 제어 문자는 \ 로 시작하는 이스케이프 시퀀스이다.
# \n : 다음 줄로 이동하며 개행이라고도 부른다.
# \t : 탭 문자, 키보드의 Tab 키와 같으며 여러 칸을 띄운다.
# \\ : \ 문자 자체를 출력할 때는 \ 를 ... |
# while True:
# print("참")
list = [1, 2, 3, 4, 5]
while 5 == 5:
print("참")
# 부울 타입 앞글자가 대문자
isData = False # True
while isData:
print("참") |
count = int(input('반복할 횟수를 입력하세요: '))
i = 0
while i < count:
print('Hello, world! %d' % i)
i += 1
# %d : 문자열 포맷 코드
# 삽입할 숫자는 % 문자 다음에 써넣는다. |
# 집합을 표현하는 세트(set)라는 자료형 제공
# 합집합, 교집합, 차집합 등의 연산이 가능
fruits = {'strawberry', 'grape', 'orange', 'pineapple', 'cherry'}
print(fruits)
# [ ] 로 특정 요소만 출력할 수 없음
a = set('apple')
print(a) # 중복된 문자는 포함되지 않는다.
b = set(range(5))
print(b)
c = set()
print(type(c))
# 빈 set 만들기
# 세트가 { } 를 사용한다고 해서 c = { }와 같이 만들면
# 빈 딕셔너리가 만... |
# if, else에서 변수에 값을 할당할 때는
# 변수 = 값 if 조건문 else 값 형식으로 축약 가능
# 이런 문법을 조건부 표현식이라고 부른다.
# 보통 람다 표현식에서 사용
x = 5
y = x if x == 10 else 0
print(y)
x = 5
if x == 10:
y = x
else:
y = 0
print(y)
# 위 표현식과 아래 조건문은 같다. |
print('=-' * 20)
print(' ' * 10, 'LOJA BALBINO')
print('=-' * 20)
print()
soma = contador = totmil = menorpreco = 0
nomemenorpreco = ' '
while True:
nomeproduto = str(input('Informe o nome do produto: ')).strip().title()
precoproduto = float(input('Informe o preço do produto: R$ '))
contador += 1
if p... |
soma = 0
cont = 0
for n in range(1, 501, 2):
if n % 3 == 0:
cont += 1
soma += n
print('A soma de todos os %i valores solicitados é igual a: %i' % (cont, soma))
|
print('{:^40}'.format(' \033[1;4;35mLOJAS BALBINO\033[m '))
print()
preco = float(input('Informe o preço do produto: R$'))
print('''Qual será a condição de pagamento?
[ 1 ] Dinheiro/cheque (\033[4;1mà vista\033[m)
[ 2 ] Cartão (\033[4;1mà vista\033[m)
[ 3 ] Até \033[4;1m2x no cartão\033[m
[ 4 ] \033[4;1m3x ou mais\03... |
import sys
def allstrings(alphabet, length):
"""Find the list of all strings of 'alphabet' of length 'length'"""
if length == 0:
return []
c = [[a] for a in alphabet[:]]
if length == 1:
return c
c = [[x,y] for x in alphabet for y in alphabet]
if length == 2:
return... |
def Chorus(count):
for i in range(count):
print("Old MacDonald had a farm, E-I-E-I-O")
def Inner(Animal, Sound):
print("And on his farm he had some", Animal, ", E-I-E-I-O")
print("With a", Sound, Sound, "here, And a", Sound, Sound, " there")
print("Here a ", Sound, ", there a", Sound, " , Everywhere a", Sound, S... |
class Solution(object):
def trapRainWater(self, heightMap):
"""
:type heightMap: List[List[int]]
:rtype: int
"""
#Brickstacks=[[3,4,5,0],[5,2,3,0],[6,4,5,0]] #the formation of bricks
Brickstacks = heightMap
Layer_n=[[0]*len(Brickstacks[0])for _ in range(len(Br... |
ThisIsAList=list()
print(ThisIsAList)
x = 8
ThisIsAList.append(x)
ThisIsAList.append(6)
print(ThisIsAList)
ThisIsAList[0] = 7
print(ThisIsAList)
for i in range(0,len(ThisIsAList)):
ThisIsAList[i]=ThisIsAList[i]*5
print(ThisIsAList)
|
# Even and Odd function
def evenOdd( x ):
if (x % 2 == 0):
print("even")
else:
print("odd")
evenOdd(2)
evenOdd(3)
|
import re as regex
pattern = "^966"
test_string = "966598739980"
result = regex.match(pattern,test_string)
if result:
print("Saudi number")
else:
print("Not Saudi number") |
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
evenOdd(2)
evenOdd(3)
evenOdd(122)
#------------------------------------------------------
# String lab:
name = "Abdullah Alsrhri"
print(name[9:])
#--------------------------------------------------------
# Loop lab
i = 1... |
import re as regex
pattern = '^(966)(5|05)[0-9]{8}'
test_string = ( input ( "Enter a number: " ) )
result = regex.match(pattern, test_string)
if result:
print("Saudi Number.")
else:
print(" Not Saudi Number.")
|
class RingBuffer:
def __init__(self, capacity):
self.capacity = capacity
self.storage = []
self.counter = 0
def append(self, item):
# if storage is less than the max capacity of the buffer
# append new item to the end of the buffer
if len(self.storage) < self.cap... |
# def my_math_func(x, f):
# return f(x)
# def x_cube(x):
# return x ** 3
# my_lambda = lambda x: x ** 3
# print(my_math_func(5, lambda x: x ** 3))
# print(my_lambda(5))
# my_letters = ['a', 'b', 'c', 'd', 'e']
# print(list(map(str.capitalize, my_letters)))
# print(list(map(lambda x:x+x.capitalize(), my_let... |
#import the os module and module for reading csv files
import os
import csv
budget_data = os.path.join("Resources","budget_data.csv") #file where data is held
#read through csv file
with open(budget_data) as csvfile:
csvreader=csv.reader(csvfile,delimiter=",")
csv_header=next(csvfile) #skip header row
#v... |
# def gcd(a, b):
from math import gcd
def sum_of_digits(m):
s = 0
while m > 0:
s += m % 10
m = m // 10
return s
for n in range(1, 100000):
a = 2009 * n + 2019 * 2014
b = 2014 * n
g = gcd(a, b)
a = a / g
if a % 1004 == 0:
print(sum_of_digits(n))
break
|
#Problem Set 1
#Part A
portion_down_payment = 0.25
current_savings = 0
r = 0.04 #investments earn a return of 4%
annual_salary = int(input("Enter your starting annual salary:")) #120000
portion_saved = float(input("Enter the percent of your salary to save in decimal:")) #0.10
total_cost = int(input("Enter cost of you... |
import csv
# csv2dict.py
#
# This script takes csv-type data files and converts them into a python dictionary with the "first" line of the csv-file read in as the "headers" and, accordingly, as the dictionary "keys."
# Created 2012Mar12 by BChoi
# Ex.: mydict = csv2dict('/Users/bchoi/Documents/Rearden_Related/Axciom_R... |
# Abstract Class
class Animal():
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement this abstract method")
class Dog(Animal):
def speak(self):
return self.name + " says woof"
class Cat(Animal)
def speak(self):
... |
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "copyright", "credits" or "license()" for more information.
>>>
"""
Tsagan Garyaeva
CS 100 2018F Section 01
HW 0, Sep 7, 2018
"""
# Exercise 5b
days_in_year = 356
age = 35
gramms_in_kg = 1000
# Exercise 5c
cost... |
# pattern1
from heapq import heappush
from heapq import heappop
def linked_heap_sort(nums: list) -> list:
heap = []
while nums:
heappush(heap, nums.pop())
while heap:
nums.append(heappop(heap))
return nums
# pattern2
def heap_sort(nums: list) -> list:
heapify(nums)
index = l... |
a = int(input())
next = a+1
prev = a-1
print("The next number for the number %i is %i." % (a,next))
print("The previous number for the number %i is %i." % (a,prev))
|
import re
import sys
STRIPPING_REGEX = r'[A-Za-z].+'
def strip_it(line):
test = re.findall(STRIPPING_REGEX, line)
if test:
return test[0]
def main():
file_names = sys.argv[-2:]
if len(file_names) > 2:
print 'Too many files'
exit(-1)
elif len(file_names) < 2:
print 'Too few files'
ex... |
def pascal_triangle(n):
tri = [[1]]
while (len(tri) < n):
prev = [0] + tri[-1] + [0]
a = []
for i in range(len(prev)-1):
a.append(prev[i] + prev[i+1])
tri.append(a)
return tri[-1]
def lattice_path(n): # solution for n x n square
return max(pascal_triangle((... |
def digit_sum(n):
if n == 0:
return 0
return (n % 10) + digit_sum(int(n / 10))
maxA = 1
maxB = 1
max = 1
for a in range(100):
for b in range(100):
s = digit_sum(a**b)
if (max < s):
maxA = a
maxB = b
max = s
print "Answer:", "a =", maxA, "b =",... |
import math
r = 1.0
l_sect = ((2 * r * 2 * r) - (math.pi * r * r)) / 4
def solve_for_x(n):
# find the x coordinate where the line between the
# lower left corner of the 1st sqaure and the upper
# right corner of thenth square intersects with the
# circle in the 1st square
n = 1.0 * n
return ... |
# Learn python at python_coderz_
def A(char):
print("")
for i in range(7):
for j in range(5):
if ((j == 0 or j == 4) and i != 0) or ((i == 0 or i == 3) and (j > 0 and j < 4)):
print("*", end=" ")
else:
print(" ", end=" ")
print("")
def B(c... |
from argparse import ArgumentParser
import json
def main(): # hi
test = False
# num_found = {selector_name : selector_count}
num_found = {}
# get local json file as command line args
parser = ArgumentParser(description='get json for input')
parser.add_argument('input', type=str, help="json fil... |
class Employee:
no_of_leaves = 8
def __init__(self,name,salary,role):
self.name = name
self.salary = salary
self.role = role
def printdetails(self):
return f"name is {self.name}. salary is {self.salary}. and role is {self.role}"
classmethod
def change_leaves(cls, ne... |
class Employee:
no_of_leaves = 8
def __init__(self, name, salary, role): #Dunder method
self.name = name
self.salary = salary
self.role = role
def printdetails(self):
return f"name is {self.name}. salary is {self.salary}. and role is {self.role}"
@classmethod
def ... |
f1 = open("twinkle.txt")
try:
f = open("does2.txt")
except Exception as e:
print(e)
except EOFError as e:
print("Print eof error aa gaya hai", e)
except IOError as e:
print("Print IO error aa gaya hai", e)
else:
print("This will run only if except is not running")
finally:
print("Run this ... |
import random
n = int(input("Enter the number of friends \n"))
name_list = input(f"Enter the name of your {n} friends \n") |
n = int(input(""))
sum = 0
while n > 0:
sum = sum+m
n = n-1
print sum
|
# your code goes here
def isIsogram(n):
charMap={}
for h in n:
if h in charMap:
return False
else:
charMap[c]=1
return True
n=raw_input().rstrip()
print("Yes" if isIsogram(n) else "No")
|
# your code goes here
n=int(input(""))
count=0
while(n>0):
count=count+1
n=n//10
print("the number of digits in the given number:",count)
|
num = int(input("enter the number"))
if num < 0:
print("the number is negative")
elif num == 0:
print("the number is zero")
else:
print("the given number is positive")
|
s = int(raw_input())
if(s < = 10):
print ("yes")
else:
print("no")
|
n = int(raw_input())
reverse = 0
while(n > 0):
remainder = n % 10
reverse = reverse* 10 + remainder
n = n/10
print reverse
|
class TreeNode:
def __init__(self, val, left=None, right=None, parent=None):
self.left = left
self.right = right
self.parent = parent
self.val = val
def __repr__(self):
return str(self.val)
root = TreeNode(6)
l1 = TreeNode(5)
l11 = TreeNode(2)
l12 = TreeNode(5)
l2 = Tre... |
from sort import heapsort, quicksort, insertion_sort, reverse, add_integers, counting_sort, radix_sort
import unittest
class TestSort(unittest.TestCase):
def test_heap_sort(self):
x = [4, 8, 2, 1, 0]
self.assertEqual(heapsort(x)[::-1], [0, 1, 2, 4, 8])
def test_quicksort(self):
x = [4,... |
if __name__ == "__main__":
Enviroment = object
from board import Board
O = "O"
X = "X"
P1 = 1
P2 = -1
else:
from ..environment import Environment, P1, P2
from .board import Board
from . import O, X
class TicTacToe(Environment):
def __init__(self, board = None):
if board... |
def fib(n):
"""returns the nth Fibonacci number"""
sequence = [0, 1]
for i in range(n + 1):
value = sequence[-2] + sequence[-1]
sequence.append(value)
return sequence[n]
|
# @Time : 2018/11/5 14:41
# @Author : Yanlin Wang
# @Email : wangyl_a@163.com
# @File : 8. WORKING WITH TEXT DATA.py
from time import clock
import pandas as pd
import numpy as np
start = clock()
s = pd.Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat'])
"""
# 对序列进行操作
s.str.lower()
s.str.u... |
# @Time : 2018/9/25 22:29
# @Author : Yanlin Wang
# @Email : Wangyl_a@163.com
# @File : TempConvert.py
def temp_convert(temp_str):
"""
华氏温度F,和摄氏温度C互相转换
:param temp_str: 输入的温度,华氏(F)or摄氏(C)
:return: 转换后的温度
"""
# temp_str = input("input your temp")
if temp_str[-1] in ['F', 'f']:
... |
# @Time : 2018/9/25 22:21
# @Author : Yanlin Wang
# @Email : Wangyl_a@163.com
# @File : print_input_format.py
print("hello,world")
# print 中间分隔符 sep
print('www', 'python', 'org', sep='.') # 以 . 分割
print('www', 'python', 'org', sep='\n') # 以 换行 分割
# print 结束符end= 默认是结束后换行, 可以改为空,则连续输出
print('hello, wor... |
""" Where's That Word? functions. """
# The constant describing the valid directions. These should be used
# in functions get_factor and check_guess.
UP = 'up'
DOWN = 'down'
FORWARD = 'forward'
BACKWARD = 'backward'
# The constants describing the multiplicative factor for finding a
# word in a particular di... |
def calcReimburse(rate, startMileage, endMileage):
return eval(f"{rate} * ({endMileage} - {startMileage}) / 100") # evaluates string representation of expression
def readFile(fileName):
with open(fileName, 'r') as file: # read in contents of file
lines = file.read().split("\n") # lines is a list of lin... |
#Write a function reverseArray(A) that takes in an array A and reverses it,
#without using another array or collection data structure; in-place.
def reverseArray(A):
if ( not A ) or ( A == 0 ):
exit("The array can not be empty")
#Begining of the index
start_index = 0
#End of the index - 1
... |
import pandas as pd
import json
#将每条评论放入list 中
def get_data(contents_all):
contents = []
for content_data in contents_all:
c = content_data.split('。')
contents.append(c)
return contents
#将评论分行写入txt 文件中
def totxt(contents):
f = open("raw data/contents.txt","w+")
for content in contents:
... |
# Uses python2
def calc_fib(n):
fib=[]
fib.append(0)
fib.append(1)
if(n>=2):
for i in xrange(2,n+1):
fib.append(fib[i-1]+fib[i-2])
return fib[i]
elif(n==1):
return 1
else:
return 0
n = int(input())
print(calc_fib(n))
|
import random
def split(L):
p = random.choice(L)
l, r = [], []
m = 0
for e in L:
if e < p:
l.append(e)
elif e > p:
r.append(e)
else:
m += 1
return l, [p] * m, r
def quickSort(L):
if len(L) <= 1:
return L
l, m, r = split(L... |
# modified to be able to store ids and values in heap.
# Heap shortcuts
def left(i): return i * 2 + 1
def right(i): return i * 2 + 2
def parent(i): return (i - 1) / 2
def root(i): return i == 0
def leaf(L, i): return right(i) >= len(L) and left(i) >= len(L)
def one_child(L, i): return right(i) == len(L)
def val_(pair)... |
#
# Given a list of numbers, L, find a number, x, that
# minimizes the sum of the absolute value of the difference
# between each element in L and x: SUM_{i=0}^{n-1} |L[i] - x|
#
# Your code should run in Theta(n) time
#
import random
def split(L):
p = random.choice(L)
l, r = [], []
m = 0
for e in L:
... |
""" Python script that contains Grid and Node class definitions.
Grid class is a two dimensional collection of Nodes that allows for a graphical and
interactive representation of the A* pathfinding algorithm.
Node class represents a single unit of the two-dimensional grid with varying states
to represent different ph... |
class Animal(object):
def __init__(self, name):
self.name = name
self.health = 100
def Walk(self):
print 'Walking'
self.health -= 1
return self
def Run(self):
print 'Running'
self.health -= 5
return self
def Display_health(self):
... |
# Nettoyer la console avant le demarrage du programme #
import os
os.system('clear')
#######################################################
##################
# counting FIZZBUZZ #
#################
num = 1
fizzes = 0
buzzes = 0
fizzbuzzes = 0
fizval = []
buzval = []
fizbuzval = []
while num <= 1000:
if ((num % 3)... |
# I want to be able to call capitalize_nested from main w/ various lists
# and get returned a new nested list with all strings capitalized.
# Ex. ['apple', ['bear'], 'cat']
# Verify you've tested w/ various nestings.
# In your final submission:
# - Do not print anything extraneous!
# - Do not put anything but pass ... |
import socket, sys
from pynput.keyboard import Key, Listener
#Create socket (allows two computers to connect)
def create_socket():
try:
global host
global port
global s
host = "10.1.10.162"
port = 9999
s = socket.socket()
except socket.error as msg:
print(... |
from collections import Counter
def vowel_count(phrase):
"""Return frequency map of vowels, case-insensitive.
>>> vowel_count('rithm school')
{'i': 1, 'o': 2}
>>> vowel_count('HOW ARE YOU? i am great!')
{'o': 2, 'a': 3, 'e': 2, 'u': 1, 'i': 1}
"""
vowels = 'aeiou'... |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 19 09:35:43 2021
@author: yerminal
@website: https://github.com/yerminal
"""
import numpy as np
mu, sigma = 0, 0.1 # mean and standard deviation
s = np.random.normal(mu, sigma, 100)
print("Mean Difference:",abs(mu - np.mean(s)))
print("STD Difference:",abs(sigma - np.std... |
# python3
import sys, threading
sys.setrecursionlimit(10**6) # max depth of recursion
threading.stack_size(2**27) # new thread will get stack of such size
class TreeOrders:
def read(self):
self.n = int(sys.stdin.readline())
self.key = [0 for i in range(self.n)]
self.left = [0 for i in range(self.n)]
... |
# P-1.29 Write a Python program that outputs all possible strings
# formed by using the characters 'c' , 'a' , 't' , 'd' , 'o' , and 'g'
# exactly once.
from typing import Dict, List
def permutate(input: str) -> None:
"""
prints out all permutations of input
Taking a recursive approach the algorithm wil... |
# R-2.6 If the parameter to the make_payment method of the CreditCard class
# were a negative number, that would have the effect of raising the balance
# on the account. Revise the implementation so that it raises a ValueError if
# a negative value is sent.
class CreditCard:
"""A consumer credit card."""
def... |
# C-1.23 Give an example of a Python code fragment that attempts to write an ele-
# ment to a list based on an index that may be out of bounds. If that index
# is out of bounds, the program should catch the exception that results, and
# print the following error message:
# “Don’t try buffer overflow attacks in Python!”... |
import sys
def print_odd_numbers():
"""
:rtype: None
"""
for x in range(1, 101):
if x % 2:
print x
def print_mult_tables():
for x in range(1, 13):
result = ""
for y in range(1, 13):
result += str(x * y) + ' '
print '{0} {1}'.format(x, re... |
"""
SOURCE: https://stackoverflow.com/questions/53975717/pytorch-connection-between-loss-backward-and-optimizer-step
"""
import torch
x = torch.tensor([1.0], requires_grad=True)
y = torch.tensor([2.0], requires_grad=True)
z = 3*x**2+y**3
print("x.grad: ", x.grad)
print("y.grad: ", y.grad)
# print("z.grad: ", z.grad... |
#coding=utf-8
d=lambda x:x+1 if x > 0 else 'Error'
g = lambda x:[(x,i) for i in xrange(0,10)]
print g(0)
print 'x'*10
print d(9)
print d(10)
def e(x):
return x+1
print e(12)
print d(-0)
# 函数的参数总结
# 1、位置匹配
def func(arg1,arg2):
return arg1,arg2
print func(1,2)
#2、关键字匹配
def func1(k1='',k2='None',k3=''):
... |
'''
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
'''
class Solution:
#全部组合
def threeSum(self, nums):
list1=[]
for i in range(len(nums)-2):
f... |
#coding:UTF-8
'''
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
'''
class Solution(object):
... |
# blocks a list of sites
import time
from datetime import datetime as dt
# siteblocker.py
# accesses a hostfile and edits it based on the time of day.
#
# TODO
# does not yet run as a daemon/cron (back burner)
hosts_temp = "/Users/DM-Alt/Software Dev/Python/siteblock/hosts"
hosts_path = "/etc/hosts"
redirect = "127... |
import sys
import datetime
import locale as _locale
__all__ = ["IllegalMonthError", "IllegalWeekdayError", "setfirstweekday",
"firstweekday", "isleap", "leapdays", "weekday", "monthrange",
"monthcalendar", "prmonth", "month", "prcal", "calendar",
"timegm", "month_name", "month_abbr", "... |
an_int = 5
a_float = 10
a_string = "hello"
a_bool = True
message = "hello aa "
print(an_int + a_float)
print (str(an_int) + a_string)
print(a_string + str(a_bool))
print(str(a_float) +"\n" + message )
|
x = int(input("mantepse ton ari8mo"))
number = 0
pro = 0
while number != x and pro <=5 :
if number > x:
number = int(input(("dwse ari8mo mikrotero :")))
pro += 1
else:
number = int(input(("dwse ari8mo megalutero :")))
pro += 1
if number == x :
print("to vrhkes!! einai to : " ... |
#Author: AMARACHI IWUH
print("******THE HANGMAN!!!!********")
print("Instructions:")
print("1. For the default mode, a hardcoded word will be used to generate the empty spaces.")
print("2. For the human against human game, a user will type in a random word, the computer will hide it and the opponent will try and figur... |
import numpy as np
def Swap(data,f,s):
reg = data[f]
data[f] = data[s]
data[s] = reg
def Sort(data,f,e):
pivot = data[e]
j = f
if(f<e):
for i in range(f,e):
if((data[i]< pivot) and (i!=j)):
Swap(data,i,j)
j+=1
elif(data[i]< pivot... |
"""
Node class has the data and a pointer that is used to point to the next Node object.
"""
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next_node = next_node
def get_data(self):
return self.data
def get_next(self):
return self.n... |
"""
The longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given
sequence such that all elements of the subsequence are sorted in increasing order.
For example, length of LIS for { 10, 22, 9, 33, 21, 50, 41, 60, 80 } is 6 and LIS is {10, 22, 33, 50, 60, 80}
The program's ... |
"""
There are 2 sorted arrays A and B of size n each.
Write an algorithm to find the median of the array obtained after merging the above 2 arrays
(i.e. array of length 2n). The complexity should be O(log(n))
1) Calculate the medians m1 and m2 of the input arrays ar1[]
and ar2[] respectively.
2) If m1 and m2 both a... |
"""
Given a string, find the longest possible palindromic substring.
The algorithm is solved using Dynamic Programming. Time complexity is O(n^2) and
space complexity is O(n^2). This is much better than the Brute force logic with
O(n^3) time complexity.
"""
def longestPalindromicSubString(string):
arr = list(string... |
"""
Given a graph with or without cycles, a source vertex s and a destination vertex d,
print all paths from given s to d.
The algorithm follows DFS or Depth first search strategy
"""
def all_paths_dfs(graph, start, goal):
queue = [(start, [start])]
visited = {}
visited[start] = True
paths = []
whil... |
"""
A Maze is given as N*N binary matrix of blocks where source block is the upper left most block i.e., maze[0][0]
and destination block is lower rightmost block i.e., maze[N-1][N-1].
A rat starts from source and has to reach destination. The rat can move in only 2 directions, either bottom or right.
In the maze matri... |
"""
Write a Python program to count the occurrences of each word in a given sentence.
"""
def wordFrequency(input_string):
# Initiating empty Dictionary
input_word = input_string.split(' ')
dict = {}
for n in input_word:
keys = dict.keys()
# if key exists increase by 1
if n in... |
"""
Write a Python program to sum all the items in a list.
"""
def sumListItem(input_list):
total = 0
for i in range(0, len(input_list)):
total = total + input_list[i]
return 'Sum of all items in the list : %s' % total
print(sumListItem([1, 2, 3, 4, 5]))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.