text stringlengths 37 1.41M |
|---|
import random, time
def print_guide_board():
print("7|8|9")
print("-+-+-")
print("4|5|6")
print("-+-+-")
print("1|2|3")
def new_board():
board = {"upperLeft": " ", "upperMiddle": " ", "upperRight": " ",
"midLeft": " ", "midMiddle": " ", "midRight": " ",
"b... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
dp = {}
a = 0
def find_num(n,nums):
global dp
global a
if int(nums[0:n] ) > 26:
return 0
if int(nums) < 10:
return 1
if nums[n:] == "":
num = 0
else:
num = int(nums[n:])
if num < 10:
return 1
if nums[n:] no... |
#快速排序算法,快排算法需要注意的是比较基准数大小需要送右边开始比较!!!
import time
import random
#arr = [5,12,6,25,34,15,8,9,7,2,31,22,74]
arr = []
for i in range(0,999):
arr.append(random.randrange(1 , round(time.time()/100),1))
def quicksort(left,right):
if left > right:
return
a = arr[left]
i = left
j = right
while i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class DICTIONARY():
def __init__(self):
self.data = []
self.data_dict = {}
self.read_dictionary("dictionary.txt")
self.create_dict()
def read_dictionary(self, dictionary_name):
# 辞書の読み込み
dict_data_tmp = open(dictiona... |
###QUESTION 2###
usersInt = (int(input("Give me an integer: ")))
def factorial(n):
"""Function to work out the factorial of a number"""
i = 1
while n >= 1: # Keep looping while int being used is above or equal to 1, factorials do not get multiplied by 0
i = i * n # The multiplication of 'i' with ... |
"""
price is an array of price with the length = (index+1) and the correspoding price is the value in the array
n is the length of rod
"""
def cut_a_rod(price, n):
if n <= 0:
return 0
result = 0
for i in xrange(n):
result = max(result, price[i] + cut_a_rod(price, n - i - 1))
return r... |
"""
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
"""
def subsetWithDup(nums):
result = [[]]
nums.sort()
for i in xrange(len(nums)):
if i == 0 or nums[i] != nums[i-1]:
l = len(result)
for j in xrange(len(result) - l , len(resu... |
#!/usr/bin/env python
# coding: utf-8
import requests
import pandas as pd
from time import sleep
from datetime import datetime
import sqlite3
'''
Created by: Pavithra Coimbatore Sainath
Date: 15th Apr 2021
'''
'''
This function returns the date range for the given start and end dates
This will be used to generate th... |
#!/usr/bin/env python
#
# Copyright (c) 2015
# Massachusetts Institute of Technology
#
# All Rights Reserved
#
"""
Authors: Kelly Geyer
Installation: Python 2.7 on Windows 7
File: pyTweet.py
Installation: Python 2.7 on Windows 7
Author: Kelly Geyer
Date: June 24, 2015
Description: This script ... |
'''
Input: a List of integers as well as an integer `k` representing the size of the sliding window
Returns: a List of integers
'''
def sliding_window_max(nums, k):
arr = nums
return_arr = []
n = len(arr)
beg = 0
end = beg + k
while end <= n:
current_arr = arr[beg:end]
return_arr... |
import heapq
import sys
import math
input = sys.stdin.readline
def getLength(a, b):
x1, y1 = a
x2, y2 = b
return math.sqrt(((x1 - x2) ** 2 + (y1 - y2) ** 2))
def findParent(x):
if x == parent[x]:
return x
return findParent(parent[x])
def union(x, y):
x = findParent(x)
y = findPare... |
import folium
import pandas
#Loads data from Volcanoes.txt into a DataFrame
data = pandas.read_csv("UdemyCourse\WebMap\Volcanoes.txt")
#Creates lat, long, elev, and name lists from the data frame
lat = list(data["LAT"])
lon = list(data["LON"])
elev = list(data["ELEV"])
name = list(data["NAME"])
#Changes color of the... |
def computepay(h, r):
if h <= 40 :
return h*r
else :
return (40*r + (h-40)*r)
hours = float(input("Enter hours:"))
rate = float(input("Enter rate :"))
pay = computepay(hours, rate)
print("Pay", pay) |
# 多重判断
'''
if 条件1:
条件1成立执行的代码1
...
elif 条件2:
条件成立执行的代码2
...
else:
以上条件都不成立执行的代码3
...
'''
age=int(input('请输入你的年龄:'))
# 童工
if age < 18:
print(f'你的年龄是{age}岁,为童工,不合法')
# 18-60 合法
elif 18 <= age <=60: #化简得来的
print(f'你的年龄是{age}岁,为合法工作年龄')
# 大于60退休
else:
print(f'你的年龄是{age}岁,为退休年龄')
|
#集合 --可变类型
#创建集合 --使用set()或{},但是空集合只能使用set(),因为空子典占用了{}
#集合内没用重复数据,可以去重
#1.创建有数据的集合
s1 = {10,20,30,40,50,60,70}
print(s1) #集合没有顺序,不支持下标查找
s2 = {1,1,2,3,4,4,5}
print(s2) #去重功能
s3 = set('fdsafd123') #set()创建集合,其中不能有int类型数据,而且只能有一个字符串
print(s3)
#2.创建空集合:set()
s4 = set() #空集合
print(s4) #set()
print(ty... |
# while语法
'''
while 条件:
条件成立重复执行的代码1
条件成立重复执行的代码2
...
'''
# 需求:重复打印10次
i = 1
while i <= 10:
print('巴拉')
i+=1
print("游戏结束")
'''
# 计数器习惯写法
i = 0 #计算机计数习惯性从0开始
while i < 5 : #总计还是5次(0,1,2,3,4)
'''
|
#认识字符串
# 单引号
a = 'hello' #单引号不支持回车换行
print(a)
print(type(a))
b = "TOM"
print(type(b))
# 三引号
e = '''i am TOM'''
print(type(e))
f = """I am TOM""" # 三引号支持回车换行
print(type(f))
print(f)
#I`m TOM
c = "I'm TOM"
q = 'i\'m TOM' #加上转义符号
print(c)
print(q)
#字符串输出
name = 'Tom'
print('我的名字是%s'%name)
print(f'我的名字是{name}')... |
import speech_recognition as sr
import pyttsx3
import datetime
import wikipedia
import webbrowser
import os
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
def speak(audio):
engine.say(audio)
engine.runAndWait()
# Without run... |
def shellSort(arr, N):
count = 0
interval = N / 2
while interval > 0:
for i in range(interval, N):
count += 1
temp = arr[i]
j = i
while j >= interval and arr[j - interval] > temp:
arr[j] = arr[j - interval]
j -= interval... |
#!/usr/bin/env python
# coding: utf-8
# In[2]:
#Assignment
#Spider Game
#Importing random library
import random
#Creating variables for each player
playerx1 = ["","","","","","","","","",""]
playerx2 = ["","","","","","","","","",""]
playerx3 = ["","","","","","","","","",""]
playerx4 = ["","","","","","","",""... |
# this file deletes a row of data to the table
import sqlite3
def main():
deleteRow()
def deleteRow():
# this names the database
dog_file = 'Dog_Database.sqlite'
# this names the table
dog_table = 'Dog_Table'
#this points to the dog name which we will use to delete by
dogName = "Doggo_N... |
"""
Public and Private decorators.
Public decorator allows to get and set only attributes that were passed to them during decoration.
Example: @public('data', 'size') - set and get operations will work only for 'data' and 'size'
attributes. All other attributes (if any) are private and cannot be gotten and set.
Priva... |
from auxiliary import *
def insertion_sort(arr, verbose=False):
for sort_len in range(1, len(arr)):
cur_item = arr[sort_len]
if verbose:
print('Cur item:', cur_item)
insert_index = sort_len
while insert_index > 0 and cur_item < arr[insert_index - 1]:
arr[ins... |
import smtplib
import email.utils
import sys
import mailconfig
import getpass
mailserver = mailconfig.smtpservername
From = input('From: ').strip()
To = input('To: ').strip()
Tos = To.split(';')
Subj = input('Subject: ').strip()
Date = email.utils.formatdate()
text = 'From: {0}\nTo: {1}\nDate: {2}\nSubject: {3}\n\n... |
"""exercicio036.py em 2018-10-09. Projeto Practice Python.
No exercício anterior, contamos quantos aniversários há em cada mês em nosso dicionário de aniversários.
Neste exercício, use a biblioteca Python bokeh para traçar um histograma em que meses os cientistas têm aniversários!
Como levaria muito tempo para você i... |
"""exercicio012.py em 2018-09-30. Projeto Practice Python.
Escreva um programa que tenha uma lista de números (por exemplo, a = [5, 10, 15, 20, 25]) e
faça uma nova lista apenas com o primeiro e o último elemento da lista dada.
Para praticar, escreva este código dentro de uma função.
"""
from cicero import cabecalho
... |
"""exercicio001.py em 2018-09-29. Projeto Practice Python.
tipos de strings de entrada int
Crie um programa que peça ao usuário para inserir seu nome e sua idade. Imprima uma mensagem endereçada a eles,
informando o ano em que completará 100 anos.
"""
from datetime import datetime
from cicero import cabecalho
def ... |
"""exercicio002.py em 2018-09-29. Projeto Practice Python.
entrada se tipos int números de comparação de igualdade mod
Peça ao usuário um número.
Dependendo se o número é par ou ímpar, imprima uma mensagem apropriada para o usuário.
Dica: como um número par / ímpar reage diferentemente quando dividido por 2?
Extras:... |
"""exercicio017.py em 2018-10-01. Projeto Practice Python.
Use o BeautifulSoup e solicite pacotes Python para imprimir uma lista de todos os títulos de artigos na
página inicial do New York Times.
"""
import requests
from bs4 import BeautifulSoup
from cicero import cabecalho
def decodificador(url: str):
"""Impr... |
'''kode ini akan menerima N entri sesuai yang diinput, lalu selama data yang diinput bukan -999
, maka akan menyimpan terus data-datanya sampai N entri.
Setelah N entri data disimpan, program akan memproses dan menghitung rata-rata data
, lalu data terbesar yang ada di N buah data dan juga data terkecilnya.
Syarat peng... |
a = float(input('Zadej stranu ctverce v cm: '))
cislo_je_spravne = a > 0
if cislo_je_spravne:
print('Obvod ctverce se stranou', a, 'cm je', 4 * a, 'cm')
print('Obsah ctverce se stranou', a, 'cm je', a * a, 'cm2')
else:
print('Strana musi byt kladna, jinak z toho nebude ctverec')
print('Dekujeme za pouziti... |
value = ['pes', 'kocka', 'andulka', 'kralik', 'had']
key = []
for i in value:
key.append(i[1:])
animals_dict = dict(zip(key, value))
#print(animals_dict)
sorted_animals = []
for key in sorted(animals_dict):
sorted_animals.append(animals_dict[key])
print(sorted_animals)
|
def wordCounter(string):
x = 1
i = 0
while i < len(string):
if(string[i] == ' '):
x = x + 1
i = i + 1
return x
print('\nThis program will determine the number of words in a sentence.')
|
import xlrd3
workbook = xlrd3.open_workbook('test01.xlsx')
sheet = workbook.sheet_by_name('Sheet1')
print(sheet.cell_value(0,3))
print(sheet.cell_value(1,0))
print(sheet.merged_cells) # 查看合并单元格行、列信息,数组包含四个元素(起始行、结束行、起始列、结束列)
# 给出一个单元格行列,判断一个单元格是否是合并过的
x = 2
y = 0
if x>=1 and x<5:
if y>=0 and y<1:
print(... |
#Altere o programa dado em aula para exibir os resultados no mesmo formato de uma tabuada:
#2 × 1 = 2, 2 × 2 = 4, . . .
n = int(input("Tabuada de:"))
x = 1
while x <= 10:
tabuada = n * x
print(f"{n}x{x}={tabuada}")
x = x + 1
|
a = 4
b = 2
expressao1 = (a/b)+(b/a)
expressao2 = a/b + b/a
print(expressao1 == expressao2)
expressao3 = a/(b+b)/a
expressao4 = a/b+b/a
print(expressao3 == expressao4)
expressao5 = (a+b)*b-a
expressao6 = a+b*b-a
print(expressao5 == expressao6)
#sei que eu poderia ter simplesmente colocado as expressões direto
#e fi... |
#!/usr/bin/env python3
def main():
menu = ['tuna', 'ham', 'roast beef', 'turkey', 'caprese', 'pastrami']
sandwich_orders = []
finished_sandwiches = []
print("Here is today's menu:", *menu, sep="\n* ")
order_sandwich(sandwich_orders)
make_sandwich(sandwich_orders, finished_sandwiches)
deliv... |
def wine(wine_type):
print "Mmm, yes, this will pair nicely with my %s" % wine_type
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheeses!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man that's enough for a party!"
print "Get a bl... |
a=input("enter the number: ")
if(a%2==0):
print("given value is even")
else:
print("given value is odd")
|
from math import pow
N = int(input())
def solution(N):
i = 0
M = N/2
if N in [0,1]:
return N
else:
while i <= M:
mid = int((i + M)/2)
if pow(mid, 2) > N:
M = mid - 1
elif pow(mid-1, 2) < N:
i = mid + 1
... |
lst = list(map(int, input().split()))
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr)//2]
less, equal, more = [], [], []
for i in arr:
if i < pivot:
less.append(i)
elif i > pivot:
more.append(i)
else:
equal.appen... |
"""
Extend a simple calculator. Add and Subtract has been included for you.
Your mission. If you choose to accept it, is to add the following functionality to this program.
1. Division
2. Multiplication
To run this program (I am assuming you have python installed on a windows machine.)
1. Open the command ... |
def bubblesort(arr=[]):
if arr is None or len(arr) == 0:
return arr
arr_length = len(arr)
for i in range(arr_length):
something_sorted = False
for j in range(0, arr_length - 1 - i):
if arr[j] < arr[j + 1]:
continue
something_sorted = True
... |
def selectionsort(arr=[]):
if arr is None or len(arr) == 0:
return arr
sorted_arr = []
for _ in range(len(arr)):
smallest = min(arr)
sorted_arr.append(smallest)
arr.remove(smallest)
return sorted_arr
|
class Matrix:
def __init__(self,matr):
self.matr = matr
def __str__(self):
new_matr = ''
buf2 = list(map(str, self.matr))
for i in range(len(self.matr)):
buf = ' '.join(buf2[i].split(','))
new_matr += f'{buf[1:-1]}\n'
return new_matr
def __a... |
rate = []
first_try = True
while True:
while True:
try:
element = int(input('Введите число: '))
break
except ValueError:
print('Не правильный формат данных.')
if first_try == True or element < rate[-1]:
rate.append(element)
first_try = False
... |
def int_func(new_word_list):
new_word_list = ' '.join(list(map(str.capitalize, new_word_list)))
return new_word_list
word = input('Введите слово с маленькой буквы: ').split(' ')
print(int_func(word))
|
def fact(n):
for el in list(range(1, n+1)):
if el == 1:
rez = el
yield rez
else:
rez = rez * el
yield rez
n = int(input('Введите чило: '))
for el in fact(n):
print(el)
|
from string import ascii_lowercase
def reacting(polymer):
lowest = 0
while True:
x = 0
prev_len = len(polymer)
while True:
if (polymer[x].islower() and polymer[x + 1].isupper()) or (polymer[x].isupper() and polymer[x + 1].islower()):
if polymer[x].lower() == ... |
import sys
import argparse
class Stock:
def __init__(self, name, price, shares):
self.name = name
self.price = price
self.shares = shares
def update_stock_price(self, new_price):
self.price = new_price
def update_stock_name(self, new_name):
self.name = new_name
... |
def find_pairs_of_numbers(num_list,n):
count=0
s=len(num_list)
for i in range(0,s):
for j in range(i+1,s):
if(num_list[i]+num_list[j]==n):
count+=1
return(count)
num_list=[10,30,40,50,60]
n=90
print(find_pairs_of_numbers(num_list,n))
|
def calculate(distance,no_of_passengers):
pass
price=70
ticket_cost=80
mileage=10
route_cost=(distance/mileage)*price
total_ticket_cost=(no_of_passengers*ticket_cost)
if(total_ticket_cost>route_cost):
profit=total_ticket_cost-route_cost
return profit
else:
return ... |
#!/usr/bin/python3
###########################################################################
# Script Name: rename.py
# Create Date: 06/19/2019
# Description: The purpose of this script is to rename files in a directory by
# replacing spaces with underscores, and converting all characters to lowercase.
# Author: Mr.... |
#!/usr/bin/env python
###########################################################################
# Script Name: webscraper.py
# Create Date: 12/05/2018
# Description: The purpose of this file is to enter a website url and perform a
# simple scrape of the webpage's content and parse through the text objects usin... |
#!/usr/bin/python
i = 8
if(i % 2 == 0):
print ("Even Number")
else:
print ("Odd Number")
#% means modulus
# i%2 ==0 means a number is even
def evens(set):
total=0
for el in set:
if el%2==0:
total+=el
return total
som=[1,2,3,4]
evens(som)
def get_age():
age =int( input("pl... |
# beer song using For loop
for qty in range(99,0,-1):
if(qty>1):
print(qty,"Bottles of beer on the wall,",qty,"bottles of beer")
suffix= str(qty-1) + " bottle"+('s' if (qty!=2) else '')+" of beer on the wall"
else :
print("1 bottle of beer on the wall,1 bottle of beer")
suffix="... |
tabby_cat = '\tI\'m tabbed in.'
persian_cat = 'I\'m split\non a line.'
backslash_cat = 'I\'m \\ a \\ cat'
fat_cat = '''
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
'''
print tabby_cat
print persian_cat
print backslash_cat
print fat_cat
tricky_string_1 = 'This sentence has a backspace\b\n'
tricky_... |
print 'What is your name?',
name = raw_input()
print 'Where were you born?',
birthplace = raw_input()
print 'What is your favorite sport?',
sport = raw_input()
print 'So, your name is %s, born in %s, \
and you like %s' % (name, birthplace, sport)
|
# hackerrank - Algorithms: Is Fibo
# Written by James Andreou, University of Waterloo
import math
def perfect_square(n):
r = math.sqrt(n)
return int(r + 0.5) ** 2 == n
T = int(raw_input())
for t in range(0, T):
N = int(raw_input())**2 * 5
if perfect_square(N+4) or perfect_square(N-4):
print 'IsFi... |
# hackerrank - Algorithms: Maximizing XOR
# Written by James Andreou, University of Waterloo
L = int(raw_input())
R = int(raw_input())
max = 0
for a in range(L, R+1):
for b in range(a, R+1):
if a ^ b > max:
max = a ^ b
print max |
# There are N network nodes, labelled 1 to N.
#
# Given times, a list of travel times as directed edges times[i] = (u, v, w),
# where u is the source node, v is the target node, and w is the time it takes
# for a signal to travel from source to target.
#
# Now, we send a signal from a certain node K. How long will it t... |
__author__ = 'ralph'
from math import sqrt
def is_prime(x):
if x < 2:
return False
for i in range(2, int(sqrt(x)) + 1):
if x % i == 0:
return False
return True
# filter applied to range
print([x for x in range(101) if is_prime(x)])
from pprint import pprint as pp
# Combinin... |
# using a hashtable to count individual items
# define a set of items that we want to count
items = ["apple", "pear", "orange", "banana", "apple",
"orange", "apple", "pear", "banana", "orange",
"apple", "kiwi", "pear", "apple", "orange"]
# TODO: create a hashtable object to hold the items and count... |
# Datetime Module Part I
from datetime import datetime
now = datetime.now()
print(now.date())
print(now.year)
print(now.month)
print(now.hour)
print(now.minute)
print(now.second)
print(now.time()) |
# use a hashtable to filter out duplicate items
# define a set of items that we want to reduce duplicates
items = ["apple", "pear", "orange", "banana", "apple",
"orange", "apple", "pear", "banana", "orange",
"apple", "kiwi", "pear", "apple", "orange"]
# TODO: create a hashtable to perform a filter
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Template Version: 2017-04-13
# ~~ Future First ~~
from __future__ import division # Future imports must be called before everything else, including triple-quote docs!
"""
URL, Intro to Multithreading: https://medium.com/@bfortuner/python-multithreading-vs-multiprocessin... |
#!/usr/bin/env python
"""
This code originally written by Craig Finch
https://github.com/cfinch/Shocksolution_Examples/blob/master/Plotting/matplotlib/plot_without_axes.py
"""
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.text import Text
import numpy
fig1 = plt.figure(facecol... |
def func_with_args( foo , bar , baz , **kwargs ):
""" Simple function with three named args """
print "Got named args:" , foo , bar , baz ,
if 'other' in kwargs:
print kwargs['other']
else:
print
argDict = { 'foo':1 , 'bar':2 , 'baz':3 , 'other':4 } # The dictionary will also popula... |
# -*- coding: utf-8 -*-
for i in xrange(4000):
print i,
if i > 5:
break
# "0 1 2 3 4 5 6"
import random
for i in range(10):
for j in range(10):
num = random.randrange(1,11)
print i , "," , j , ":" , num
if num > 5:
print "break"
break... |
zeros = [ [0,0,0] ,
[0,0,0] ,
[0,0,0] ]
print zeros
for rDex , row in enumerate( zeros ): # Operate on the list as we go
row[rDex] = 1
print zeros
"""
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[1, 0, 0], [0, 1, 0], [0, 0, 1]]
""" |
# -*- coding: utf-8 -*-
""" URL, Priority Queue: https://en.wikipedia.org/wiki/Priority_queue
A priority queue is an abstract data type which is like a regular queue or stack data structure,
but where additionally each element has a "priority" associated with it. In a priority queue, an element with
high priority is... |
class Foo:
""" A silly class for testing membership """
def __init__( self ):
""" Init some silly vars """
self.bar = 1
self.baz = 2
def check_for_baz( self ):
""" Check if this instance has a baz """
return hasattr( self , 'baz' )
xur = Foo()
... |
# -*- coding: utf-8 -*-
foo = lambda x, y: (x+y, x-y) # OK : lambda can return one value
#bar = lambda x, y: x+y, x-y # ERROR : Cannot use multiple returns as you can with a def function, with lambda you must
# pack multiple values into a single structure if multiple values must ... |
#!/usr/bin/env python
"""
RESULT: If the elements in a list are themselves iterables , you can decompose the nested elements with the pattern:
'for [ subElem1 , subElem2 ] in superList'
for a list that takes the form
superList = [ ... , [ i1 , i2 ] , ... ]
"""
from random import randint
li... |
# -*- coding: utf-8 -*-
def cls_declare_print(clsName):
print "Class",clsName,"was declared!"
class Foo(object):
cls_declare_print('Foo')
def __init__(self):
print "One new Foo!"
class Bar(object):
cls_declare_print('Bar')
def __init__(self):
print "One new Bar!"
... |
import os
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def plot_a_sequence_of_images(list_arr):
"""
:param list_arr: list of 2d arrays of the same dimension
:return: animation having the sequence of images as input
"""
fig = plt... |
# 1. fill in this class
# it will need to provide for what happens below in the
# main, so you will at least need a constructor that takes the values as (Brand, Price, Safety Rating),
# a function called showEvaluation, and an attribute carCount
import sys
class CarEvaluation:
'A simple class that represents a c... |
__author__ = 'Mohan Kandaraj'
import Tkinter
import sys
import tkFileDialog
from scipy.optimize import curve_fit
import numpy
import matplotlib.pyplot as pyplot
def linear_regression(data):
"""Compute Linear Regression for univariate model"""
x_values = [x for x, y in data] #Get x values
y_values = [y for ... |
# 예외처리
import random
def numguess(try_cnt = 5, answer = random.randint(1, 100)):
while True:
if try_cnt == 0:
print("your try Count is sold out\n Correct is {}".format(answer))
break
try:
your_input = int(input("input the answer : "))
except Exception as... |
"""
The xml_simple_reader.py script is an xml parser that can parse a line separated xml text.
This xml parser will read a line seperated xml text and produce a tree of the xml with a document element. Each element can have an attribute table, childNodes, a class name, parentNode, text and a link to the document elem... |
print("구구단 몇단을 계산할까요?")
number = input()
print("구구단 " + number + "단을 계산합니다")
for i in range(1,10):
result = int(number)*i
print (number, "X", i, "=", result)
# + 사용시 int값과 str값을 연산할수 없다는 오류가 나옴!
|
str = "I love you"
reverse = ""
for char in str:
# str의 첫번째 인덱스 부터 char에 대입
reverse = char + reverse
# reverse의 첫번째 인덱스값이 밀려나면서 계속 대입됨
# "I" -> " I" -> "l I" -> "ol I".....
print (reverse)
|
'''
Leetcode - 887. Super Egg Drop
Time complexity - O(K*N)
space complexity - O(K*N)
Approach - DP
1) First, we need to create Trys+1 and k+1 matrix
2) At each cell we need to find maximum number of floors required for x trys and y eggs.
3) At particular cell when we reach >= N floors... |
"""
Python File Open
The key function for working with files in Python is the open() function.
The open() function takes two parameters; filename, and mode.
There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Appe... |
# Filename: samanthasjw_p01q02.py
# Name: Samantha Siau Jing Wen
# Description: Input radius and length of a cylinder and computes its volume
# Prompt user for radius in m
radius = float(input("Enter radius of cylinder in m: "))
# Prompt user for length in m
length = float(input("Enter length of cylinder in m: "))
... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
carrying = 0
result ... |
import random
def clear_output():
print('\n' * 50)
# Step 1: Write a function that can print out a board. Set up your board as a list, where each index 1-9 corresponds with a number on a number pad, so you get a 3 by 3 board representation. The first item in the list is a throwaway.
def display_board(board):
prin... |
#!/usr/bin/env python
# Charley Schaefer, University of York, 2020
# CLUSTER DETECTION - conditional dilation algorithm
# > scan elements of 2D binary matrix
# > find a 'seed' (a matrix element with value 1)
# > dilate the seed to find 4-connected matrix elements
# (referred to as a cluster)
# get_cluster_... |
'''
Never give file name similar to module name.
eg. numpy,array,pandas,matlab,List,etc.
numpy:
1.It is extended version of array.
2.It is use for do complex numeric calculation like matrix operation
3.numpy library is written in C language
4.It is use in data science
To install ... |
'''
Abstraction:
To hide some data.
We only declare function in abstract class and we can define it when needed.
Interface:
It Only contain all function with declaration.
Difference between Abstract Class and Interface:
Abstract Class ... |
'''
Loops:
Some lines of code we want use repeately upto certain condition then we use loop.
Ther are 3 types of loops:
1.while
2.for
3.do while.
While loop:
Syntax:
................code..............
initialization
wh... |
#To check odd and even Number
a=int(input("Enter number to check whether it is ood or even"))
if a%2==0:
print("Number is Even")
else:
print("Number is odd")
|
##Python
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
length = len(matrix)
for i in range(int(length/2)):
matrix[i],matrix[length-1-i] = matrix[length-1-i],matrix[i]
for ... |
#https://leetcode.com/problems/super-ugly-number/discuss/169815/Python-DP-solution-beats-93.7-extremely-detailed-explanation
class Solution:
"""
@param n: a positive integer
@param primes: the given prime list
@return: the nth super ugly number
"""
def nthSuperUglyNumber(self, n, primes):
... |
'''
Created on Aug 17, 2019
@author: amitbatajoo
'''
#
# from chatterbot import ChatBot
# from chatterbot.trainers import ChatterBotCorpusTrainer
#
# bot = ChatBot('MyChand')
# bot.set_trainer(cha)
#
# conversation=open('chats.txt').readlines()
# bot.train(conversation)
#
# while True:
# messa... |
#!/usr/bin/python
def printMax(a, b):
if a > b:
print(a, 'is max')
elif a == b:
print(a, 'is equal to ', b)
else:
print(b, 'is max')
#printMax(3,4)
a = int(input('a:'))
b = int(input('b:'))
printMax(a, b)
x = 50
def func():
global x
print('x is',x)
x = 2
print('Change x to',x)
func()
print('x is still',... |
def game_of_life_generator(seed):
game = GameOfLife(seed)
while True:
yield game.tick()
class GameOfLife(object):
def __init__(self, seed):
self.alive_cells = seed
def tick(self):
self.alive_cells = set.union(self.survivors(), self.births())
return self.alive_cell... |
# --------------------------------------------------------------------------
# Simple web server route that serves database information from buspatrol.db
# By Hajrudin Satrovic
# --------------------------------------------------------------------------
import sqlite3
import sys
from flask import Flask, jsonify, reque... |
test_integer = 1000
print(test_integer + 10) # 加算(足し算)
print(test_integer - 10) # 減算(引き算)
print(test_integer * 10) # 乗算(掛け算)
print(test_integer / 10) # 除算(割り算)
test_str = '1000'
print(int(test_str) + 1000)
test_str = '1000.5'
print(float(test_str) + 1000)
test_float = .5
print(test_float)
test_c... |
value = 3
if value == 1:
print('valueの値は1です')
elif value == 2:
print('valueの値は2です')
elif value == 3:
print('valueの値は3です')
else:
print('該当する値はありません')
value_1 = 'python'
value_2 = 'sgt'
if value_1 == 'Python':
pass
elif value_1 == 'python' and value_2 == 'sgt':
print('2番目の条件式がTrue')
elif val... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.