text stringlengths 37 1.41M |
|---|
string1 = str(input())
string2 = str(input())
if string1.lower() < string2.lower():
print("-1")
elif string1.lower() > string2.lower():
print("1")
else:
print("0")
|
student_heights = [180, 124, 165, 173, 189, 169, 146]
total = 0
number_of_students = len(student_heights)
for height in student_heights:
total += height
print(f"The total height for this group is {total}")
average = total/number_of_students
print(f"The average height for this group is {average}")
|
length = int(input("Largo de la lista: "))
numberList = []
while( length ):
newNumber = int(input("Elemento nuevo: "))
numberList.append( newNumber )
length -= 1
print("Numeros menores a 5:")
for number in numberList:
if( number < 5 ):
print(str(number), end=" ")
|
import datetime
todays = datetime.datetime.now()
name = input("Please enter your name: ")
age = input("Please enter your age: ")
age = int(age)
yearsLeft = 100 - age
res = todays.year + yearsLeft
print("You will be 100 years old in " + str(res))
|
# def cortar (v)
# b=v.copy()
# b.pop()
# b.pop(0)
# print(b)
# a=[1,2,3,4,5,6,7]
#cortar(a)
def Orden(a):
c=[]
c=a.sort(a)
print(a)
print(c)
if(c!=a):
print("FALSE")
else:
print("TRUE")
def Ingresar():
a =[]
b =[]
while(a!="1"):
... |
import pandas as pd
import os
from math import *
def get_spherical_distance(lat1,lat2,long1,long2):
"""
Get spherical distance any two points given their co-ordinates (latitude, longitude)
"""
# print lat1," ", lat2," ",long1," ",long2
# print type(lat1)," ", type(lat2)," ",type... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import random
name = ['万前','梁栋','张毅','李政','周煜林','谢雄鑫']
win = random.choice(name)
print(f"恭喜{win}!你中了一个没有奖金的大奖!") |
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 2 14:25:54 2021
@author: Dahire
"""
#LISTS[]
#lists are surrounded by square brackates and oblects are separated by commas
#creating a list
var=['A','C','z',10,2.5,['ab','xy'],'name']
fruits=['apple','banana','guava']
cities=['raigarh','raipur','bilaspur']
... |
def make_great(magicians,changes):
while magicians:
change = "The Great " + magicians.pop()
changes.append(change)
def show_magicians(magicians):
for magician in magicians:
print(magician)
magicians = ["wang", "hu", "zhao"]
changes = []
make_great(magicians, changes)
show_magicians(cha... |
"""用户类"""
class User():
"""存储用户的信息"""
def __init__(self, first_name, last_name, gender, age):
"""初始化用户的属性"""
self.first_name = first_name
self.last_name = last_name
self.gender = gender
self.age = age
def describe_user(self):
"""打印用户的信息"""
print("Th... |
cats = {'mi': 'wang', 'cici': 'kun'}
dogs = {'cathey': 'hu', 'eric': 'hua'}
pets = [cats, dogs]
for pet_owner in pets:
for pet_name, owner_name in pet_owner.items():
print(pet_name.title() + ' belongs to ' + owner_name.title() + '.')
|
"""例题13.6角色(飞船)和球(外星人)代码"""
import pygame
from alien_settings_13_6 import Settings
from alien_game_stats_13_6 import GameStats
from alien_ship_13_6 import Ship
from alien_ball_13_6 import Alien
import alien_game_functions_13_6 as gf
from pygame.sprite import Group
def run_game():
# 初始化pygame、设置和屏幕对象
pygame.ini... |
# Another O(n log n) sorting mechanism
# We sort by picking a pivot point to compare against
import time
import random
# randomly picks a value to pivot
def quick_sort_naive(array, debug=False, verbose=False):
start = time.time()
sorted_array = _quick_sort_naive(array, debug, verbose)
end = time.time()
... |
from .binary_tree import BinaryTree
class BinarySearchTree(BinaryTree):
def insert(self, value):
self.root = self._insert(self.root, value)
def _insert(self, node, value):
if node == None:
return self._create_node_for(value)
if value < node.value:
node.left = ... |
class TrieNode(object):
def __init__(self, key=None, parent=None):
# value should be hashable
self.key = key
self.parent = parent # of TrieNode type
self.children = {} # dictionary where key is key and value is node
self.is_terminating = False
# def __str__(self):
... |
#Первый сценарий Python
import sys #Загрузить библиотечный модуль
print(sys.platform)
print(2**100) #Возвести 2 в степень
x="spam!"
print(x*8) #Повторить строку
input()
|
#5. Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами.
# Программа должна подсчитывать сумму чисел в файле и выводить ее на экран.
with open('hw_5_5_text.txt', "w", encoding="utf-8") as numbers_file:
sum_numbers = 0
numbers = input('please insert some numbers ... |
#2. Для списка реализовать обмен значений соседних элементов, т.е.
# Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д.
# При нечетном количестве элементов последний сохранить на своем месте.
# Для заполнения списка элементов необходимо использовать функцию input().
my_list = list(input("Пожалуйста введи... |
# Shows inventory if player inputs
# 'open inventory' action
import enemy as enemy
import game_map as game_map
inventory_list = []
def open_inventory():
print(f"""\nWhat would you like to see?
Type 'quit' when finished: {inventory_list}""")
prompt = 'ACTION: '
while True:
key = input(prompt)
if key ... |
# Quits the game if the player inputs
# 'quit game' option during the game
def quit_game():
prompt = """Are you sure you want to quit?
(type yes or no) """
while True:
key = input(prompt)
if key == 'yes':
print("Quitting game...")
import sys
sys.exit()
elif key == 'no':
print(... |
"""Functions to humanize values."""
def humanize_list(value):
"""
Humanizes a list of values, inserting commas and "and" where appropriate.
========================= ======================
Example List Resulting string
========================= ======================
``["... |
import os
import string
def rename_file():
""" the function opens specific folder, lists it, and then removes all didgits from the
the file name and renames the files in our folder"""
file_list = os.listdir("D:/Users/pbutkowski/Desktop/prank")
saved_path = os.getcwd()
os.chdir("D:/U... |
# -*- coding: utf-8 -*-
import numpy as np
from pandas import Series, DataFrame
print '用字典生成DataFrame,key为列的名字。'
data = {'state':['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'],
'year':[2000, 2001, 2002, 2001, 2002],
'pop':[1.5, 1.7, 3.6, 2.4, 2.9]}
print DataFrame(data)
print DataFrame(data, columns = ['... |
from math import pi, sin, cos, acos
from FC2 import utils
from FC2 import linkList
class Itenerary:
"""This class creates the required list of
dictionaries that will hold all the required
values like Latitude, Longitude and the Euro conversion
price for the airport"""
def __init__(self):
... |
from FC2 import utils
class LinkList:
"""This is representation of a linked List"""
def __init__(self):
self.__linkList = [] # A list to hold a node of a linked List
# A node represented as a list
# A node will have two values [pointer,value]
# Pointer will point to the next nod... |
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a list of integers
def __init__(self):
self.stack=[]
def leftMost(self,root... |
class Solution:
# @param s, a string
# @return a boolean
def isPalindrome(self, s):
if len(s)==0 or len(s)==1: return True
start,end=0,len(s)-1
while start<end:
if not (s[start].isalpha() or s[start].isdigit()):
start+=1
continue
... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def inorder(self, root, ind, trange):
if ind > trange[1]: trange[1] = ind
if ind < trange[0]: trange[0] =... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a ListNode
def deleteDuplicates(self, head):
before=head
if head==None: return head
else: after=h... |
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a tree node
def inorder_traverse(self,root,result):
if root.left!=None:
... |
class Solution:
# @return a boolean
def isInterleave(self, s1, s2, s3):
if len(s1)+len(s2)!=len(s3): return False
if s1=='':
return s2==s3
if s2=='':
return s1==s3
#now we have all non-empty set
pre=[False]*(len(s1)+1)
cur=[False]*(len(s1)+... |
def recur_fibo(n):
if n<=1:
return n
else:
return(recur_fibo(n-1)+recur_fibo(n-2))
nterms=20
if nterms<=0:
print("please enter a positive number")
else:
print("fibonnaci sequence:")
for i in range(nterms):
print(reccur_fibo(i))
|
import time #? to sleep
from datetime import datetime #? birthday calculation
from datetime import date #? learning today
import webbrowser as wb #? url opering
from functools import wraps #? decorator
#? getting birth date
date_of_birth = datetime.strptime(input(
'Please, enter the "birthday" of whom will be... |
# -*- coding: utf-8 -*-
"""
Responsible for finding the regions of interest (subimages) on a given image.
"""
import cv2
import utilities as utils
def find_contours(image):
""" Given an image, it finds all the contours on it.
Just an abstraction over cv2.findContours
Parameters
----------
image : ... |
import matplotlib.pyplot as plt
def letter_subplots(axes=None, letters=None, xoffset=-0.1, yoffset=1.0, xlabel=None, ylabel=None, **kwargs):
"""Add letters to the corners of subplots. By default each axis is given an
upper-case bold letter label.
axes: list of pyplot ax objects.
letters: list of string... |
from tkinter import *
from tkinter.ttk import *
pantalla=Tk()
pantalla.title('COVID Estados')
pantalla.geometry('400x240')
opcion=StringVar()
etiesta=Label(pantalla,text='Estados')
etiesta.place(x=170,y=10)
coahuila=Radiobutton(pantalla,text='Coahuila',value='Coahuila',variable=opcion)
coahuila.place(x=160,y=40)
nu... |
an=int(input('anul = '))
an -= 2000
if an % 12 == 0:
print('Este anul dragon')
if an % 12 == 1:
print('Este anul sarpe')
if an % 12 == 2:
print('Este anul cal')
if an % 12 == 3:
print('Este anul oaie')
if an % 12 == 4:
print('Este anul maimuta')
if an % 12 == 5:
print('Este anul coc... |
from typing import List
class Solution:
def wiggleMaxLength(self, nums: List[int]) -> int:
up, down = 1, 1
for i in range(1, len(nums)):
if nums[i] > nums[i - 1]:
up = down + 1
if nums[i] < nums[i - 1]:
down = up + 1
return 0 if 0 == ... |
class Solution:
def longestSubstring(self, s: str, k: int) -> int:
if k > len(s):
return 0
for c in set(s):
if s.count(c) < k:
return max(self.longestSubstring(i, k) for i in s.split(c))
return len(s)
if __name__ == "__main__":
solution = Solutio... |
from typing import List
class Solution:
def majorityElement(self, nums: List[int]) -> int:
num = nums[0]
count = 0
for each in nums:
if count == 0:
num = each
count = count + 1 if each == num else count - 1
return num
if __name__ == "__main... |
from typing import List
class Solution:
def arrayPairSum(self, nums: List[int]) -> int:
nums.sort()
result, i = 0, len(nums)
while i > 0:
result += nums[i - 2]
i -= 2
return result
if __name__ == "__main__":
solution = Solution()
ret = solution.arr... |
from typing import List
class Solution:
def generateParenthesis1(self, n: int) -> List[str]:
res = []
left, right, length = 0, 0, 0
def backtrace(trace: str):
nonlocal left, right, length
if length == 2 * n:
res.append(trace)
return
... |
"""The game of life algorithm.
"""
import numpy as np
def compute_next_state(matrix):
"""Returns the next state of a matrix according to the game of life algs.
Parameters
----------
matrix: array
A matrix with entities 1 or 0 (live or dead)
Returns
-------
next_matrix: array
... |
def password_gen():
import random
uppers = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
lowers = list('abcdefghijklmnopqrstuvwxyz')
digits = list('1234567890')
password = uppers.pop(random.randint(0, len(uppers)-1))
password += lowers.pop(random.randint(0, len(lowers)-1))
password +... |
import time
numeropar=0
multiplo3=0
menu="si"
while menu =="si":
numeropar=int(input("Dime un Nº:\n"))
if numeropar%2==0:
multiplo3=numeropar
print ("PAR")
time.sleep (1)
else:
print ("IMPAR")
time.sleep (1)
if multiplo3%3==0:
print ("Multiplo de 3")
time.sleep (1)
else:
print ("No es multiplo de 3... |
from typing import List
from cryptoxlib.Pair import Pair
def map_pair(pair: Pair) -> str:
return f"{pair.base}-{pair.quote}"
def map_multiple_pairs(pairs : List[Pair], sort = False) -> List[str]:
pairs = [pair.base + "-" + pair.quote for pair in pairs]
if sort:
return sorted(pairs)
else:
... |
#! /usr/bin/env python3
# First notice we are importing the fuctions from the "collections" class.
# We need to do this to gain access to the functions. They are not part of
# the default name space.
from collections import OrderedDict, defaultdict, deque, Counter, namedtuple
from datetime import datetime, timedelta
... |
#!/usr/bin/env python3
# _*_ coding: utf-8 _*_
"""Template file for python 3 script"""
# import os
# import sys
import argparse
# import datetime
def main():
"""[docstring/purpose
of this script]"""
args=parse_arguments()
print("Required arg: ",args.requiredArg)
if args.optionalArg :
p... |
"""dumb json to jina2 template renderer
"""
import argparse
import jinja2
import json
import sys
def render(data, template):
"""render jija2 template
Args:
data(obj): dict with data to pass to jinja2 template
template(str): jinja2 template to use
Returns: string, rendered all, or pukes wit... |
'''
The Utopian Tree goes through 2 cycles of growth every year. Each spring, it doubles in height. Each summer, its height increases by 1 meter.
Laura plants a Utopian Tree sapling with a height of 1 meter at the onset of spring. How tall will her tree be after
growth cycles?
For example, if the number of gr... |
import tkinter as tk
import numpy as np
import math
from tkinter import *
class game ():
def __init__ (self, WindowW = 1000, WindowH = 800):
self.Window = Tk()
self.WindowW = WindowW
self.WindowH = WindowH
self.initWindow()
def initWindow(self):
self.CarW = 30.0
... |
##输入一个int型整数,按照从右向左的阅读顺序,返回一个不含重复数字的新的整数。
##输入一个int型整数
##按照从右向左的阅读顺序,返回一个不含重复数字的新的整数
###!/usr/bin/python
### -*- coding: UTF-8 -*-
##
##str = "-";
##seq = ("a", "b", "c"); # 字符串序列
##print str.join( seq );
##a-b-c
a = input()
b = []
for i in a[::-1]:
if i not in b:
b.append(i)
print(''.join(b... |
sum = 0
for i in range (101):
if i%2 == 0 :
sum += i
print(sum) |
str_in1 = 'abcdefyux' #input("输入字符串1:")
str_in2 = 'abcrdeqyux' #input("输入字符串2:")
str_out = "1"
str_list = []
length = 0
longest_list = []
last_statioin = -1
for i in str_in1:
if str_in2.find(i) >= 0 :
if str_in2.find(i) != last_statioin + 1 :
str_list.append(str_out[1:])
str_out = "1... |
##int() 函数用于将一个字符串或数字转换为整型。
##class int(x, base=10), 默认x为10进制数据,转换成10进制整形数据
##int(x, base=16),认为输入是16进制数据,将其转化为10进制整形
print( int(input(), base=16))
|
def factorial_using_for_loop(num):
fact = 1
if num < 0:
print("Not possible")
return -1
elif num == 0:
return 1
else:
for i in range(1, num+1):
fact *= i
return fact
print(factorial_using_for_loop(0)) |
#Initially create a DataBase in MySQL
#Create a table with AccNo,Name,Deposit,Withdraw
#Give a AccNo,Name, Deposit,Withdraw for Initials
#Next follow below process
#Note: Transaction is a table name in database
import mysql.connector
import sys
#BANK DETAILS;
class Bank:
def __init__(self):
... |
# -*- coding: utf-8 -*-
'''
4、编写程序,完成以下要求:
提示用户进行输入数据
获取用户的数据数据(需要获取2个)
对获取的两个数字进行求和运行,并输出相应的结果
'''
import re
def add(l):
return int(l[0]) + int(l[1])
a = input('请输入两个数字,用逗号或空格隔开:')
if re.match(r'^(\d*)([\s\,\;]+)(\d*)$', a):
al = re.split(r'[\s\,\;]+', a)
if len(al) != 2:
print('输... |
"""
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
"""
def isPalindrome(x):
"""
:type x: int
:rtype: bool
"""
l = list(str(x))
l.reverse()
n = ''.join(l)
return str(n) == str(x)
# 高级做法
# str(x)[::-1] == str(x)
print(isPalindrome(78987))
|
class StringFmt:
def __init__(self, append_zero=False, char_sz=1, to_lower=False, to_upper=False):
self._append_zero = append_zero
self._char_sz = char_sz
self._to_lower = to_lower
self._to_upper = to_upper
def format(self, s):
zero_char = "\x00" * self._char_sz
... |
#!/usr/bin/env python3
filename = input('Enter file path:')
try:
f = open(filename)
print(f.read())
f.close()
except FileNotFoundError as err:
print('Erro: {0}'.format(err))
|
#!/usr/bin/env python
'''
Created on 12/20/14
@author: EI
'''
# Written by Tim Ioannidis Mar 12 2015 for HJK Group
# Dpt of Chemical Engineering, MIT
##########################################################
######## Defines class of 3D molecules that #############
######## will be used to manipulate ####... |
"""
Title: "Special sum" function
Name: Ayan A.
Date: 21/07/2021
Description: A function that performs a special sum of its elements.
It follows the following logic - if array equals this [5, 2, [7, -1], 3, [6, [-13, 8], 4]] for instance,
then the output of the function is equal to 5 + 2 + 2 * (7 – 1) + 3 + 2 * (6 + 3 ... |
import csv
import sqlite3
def create_csv(j):
conn = sqlite3.connect('example.db')
conn.text_factory = str
cur = conn.cursor()
data = cur.execute("SELECT * FROM nmea"+str(j))
with open('file'+str(j)+'.csv', 'w') as f:
writer = csv.writer(f)
writer.writerow(['time', 'latitu... |
"""
Description: This is a simple program to create a class precende list.
We used the simple topological sorting algorithm which uses stacks to create the list.
The only change we made is that the original algorithm considers all the nodes in the graph
to order them. In our program we only start with a single node... |
## 日付・時間
import datetime
lvm ='*'*20
##3.1 日付の取得
today = datetime.date.today()
todaydetail = datetime.datetime.today()
print(lvm)
print(today)
print(todaydetail)
print(lvm)
print(today.year)
print(today.month)
print(today.day)
print(todaydetail.year)
print(todaydetail.month)
print(todaydetail.day)
print(todaydetail.mi... |
import redis
# HostAddress=str(input())
# Port=int(input())#输入测试
# 建立连接
HostAddress = "127.0.0.1"
Port = 6379
r = redis.Redis(host=HostAddress, port=Port, db=0) # 指定0号数据库
# redis-py 使用 connection pool 来管理对一个 redis server 的所有连接,避免每次建立、释放连接的开销。
# 默认,每个Redis实例都会维护一个自己的连接池。
# 可以直接建立一个连接池,然后作为参数 Redis,这样就可以实现多个 Redis 实例共享... |
"""
DFS in Python
A
/ \ \
B C D
/ /
F E
"""
class Tree(object):
def __init__(self, name='root', children=None):
self.name = name
self.children = []
if children is not None:
... |
import argparse
def get_args():
p = argparse.ArgumentParser()
p.add_argument("-i", "--input", type=str)
p.add_argument("-o", "--output", type=str)
return p.parse_args()
args = get_args()
def sort(array):
for i in range(1, len(array)):
k = i
while k > 0 and array[k] < ... |
#!/usr/bin/env python
def main():
with open('rosalind_hamm.txt', 'r') as doc:
sequence = doc.read().split('\n')
Hamming_distance = 0
for a in range(len(sequence[0])):
if sequence[0][a] != sequence[1][a]:
Hamming_distance += 1
print(Hamming_distance)
if __name__... |
from __future__ import print_function
import os
# Start of program
def main():
file = open(SelectFile("prog.txt"), 'r') # Opens the file
asm = file.readlines() # Gets a list of every line in file
program = [] # Whats this? list
for line in asm: # For every line in the asm file
... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
def compareList(sumArray,a,n):
if(n == 1):
return True
sumFirstHalf = a[0]
for z in xrange(1,n-1):
sumSecondHalf = sumArray - sumFirstHalf - a[z]
if(sumFirstHalf == sumSecondHalf):
return Tr... |
def partition(array, lo, hi):
pivot_index = hi
pivot_value = array[pivot_index]
store_index = lo
for i in range(lo, hi):
if array[i] <= pivot_value:
array[i], array[store_index] = array[store_index], array[i]
store_index += 1
array[pivot_index], array[store_... |
'''
# Function to read data from excel file
# and create derived dataframe for insertion into the database
'''
# %%
import pandas as pd
def read_angle_data(input_excel):
# read complete excel file
xls = pd.ExcelFile(input_excel)
#xls = pd.ExcelFile('Angle_violation.xlsm')
# get date from file name
... |
import matplotlib.pyplot as plt
import math
import random
def plot_points(points, ax=None, style={'marker': 'o', 'color':'b'}, label=False):
"""plots a set of points, with optional arguments for axes and style"""
if ax==None:
ax = plt.gca()
for ind, p in enumerate(points):
ax.plot(p.real, p... |
"""
Basic implementation of a stack in python
Stack:
a collection of objects insertd and removed acc. LIFO (last-in, first-out) principle
hint: think PEZ dispenser (can only access pez at "top" of stack)
Stack ADT formally supports:
s.push()
add element to the top of stack
s.p... |
def checkValidString(s):
characters = [["(",")"], ['(', '*'],['*', ')']]
open_ = []
star=[]
if len(s) == 1 and s !="*":
return False
for c in range(len(s)):
if (s[c] == '(') :
open_.append(c)
elif (s[c] == '*'):
... |
i=input(" ܼ Էּ:")
for j in range(1,10):
x=i*j
print "{}*{}={}".format(i,j,x)
|
def hanoi(n,a,b):
if n>0:
hanoi(n-1,a,total[0])
print "moving plate%s from %s to %s."%(n,a,b)
hanoi(n-1,total[0],b)
n=int(raw_input('please input number of plates: '))
total=['a','b','c']
total.remove('a')
total.remove('b')
hanoi(n, 'a','b') |
# Encapsulation
#
class Cars:
def __init__(self,speed, color):
self.__speed = speed
self.__color = color
def set_speed(self,speed):
self.__speed = speed
def get_speed(self):
return self.__speed
ford = Cars(250, 'green')
nissan = Cars(300, 're... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 1 15:07:24 2020
@author: Carlos Luco Montofré
"""
def validaEntero():
notValido = True
while notValido:
entrada =input()
try:
numero = int(entrada)
notValido = False
except ValueError:
... |
"""
Homework Assignment #3: "If" Statements
Details:
Create a function that accepts 3 parameters and checks for equality between any two of them.
Your function should return True if 2 or more of the parameters are equal, and false is none of them are equal to any of the others.
Extra Credit:
Modify your functio... |
"""
You have two very large binary trees: T1, with millions of nodes,
and T2, with hundreds of nodes. Create an algorithm to decide if T2 is a subtree of T1
That is, if you cut off the tree at node n, the two trees would be identical.
note: tree mactching can be identical to string matching, 2 solutions, trade off bet... |
"""
9.6 Implement an algorithm to print all valid (i.e., properly opened and closed) combinations of n-pairs of parentheses.
EXAMPLE:
input: 3 (e.g., 3 pairs of parentheses)
output: ((())), (()()), (())(), ()(()), ()()()
(, left = 1, right = 0
((, left = 2, right = 0
((), left = 2, right = 1
(()(, left = 3, right = 1
... |
"""__author__ = 'anyu'
4.3 Given a sorted (increasing order) array with unique integer elements,
write an algorithm to create a binary search tree with minimal height.
One way to implement this is to use a simple root.insertNode(int v) method
This will indeed construct a tree with minimal height but it will not do so... |
"""__author__ = 'anyu'
9.5 Write a method to compute all permutations of a string
This solution takes 0(n !) time, since there are n! permutations. We cannot do better than this.
"""
def permurecursive(s):
if len(s)<=1: return [s]
result =[]
for perm in permurecursive(s[1:]):
result += [perm[:i]+s[... |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 24 19:27:25 2020
@author: Vladimir Trotsenko
"""
#########################
#### ASSIGNIMENT ########
#########################
#### FIRST ##############
#########################
annual_salary = float(input('Enter the starting annual salary: '))
portion_sa... |
# mnha solução para o desafio de um contador:
# cont_plus = 0
# cont_less = 10
# while cont_plus <= 10 and cont_less >= 0:
# print(cont_plus, cont_less)
# cont_less -=1
# cont_plus +=1
#solução do professor para o desafio de um contador:
# for p, r in enumerate(range(10,1,-1)):
# print(p, r)
# print... |
#Exercicio1
#conversão em inteiro
#usando: try and except, para conseguir testar o sucesso
num1 = input('Digite um número: ')
num2 = input('Digite outro número: ')
try:
num1 = int(num1)
num2 = int(num2)
divnum1 = num1 % 2
divnum2 = num2 % 2
if divnum1 == 0 and divnum2 == 0:
print('Os doi... |
def conferter_numero(valor):
try:
valor = int(valor)
return valor
except ValueError:
try:
valor = float(valor)
return valor
except:
pass
def soma(a, b):
soma = a + b
print(soma)
def subtr(a, b):
subtracao = a - b
print(subtrac... |
# Bubble Sort
def bubblesort(alist):
for i in range(0, len(alist)-1):
print('Langkah ke-%d: '% (i+1), end='')
for j in range(len(alist)-1, i, -1):
if alist[j] < alist[j-1]:
temp = alist[j]
alist[j] = alist[j-1]
alist[j-1] = temp
pri... |
# Private Method
class rectangle:
def __init__(self, l=0, w=0):
self.__length = l
self.__width = w
def setvalue(self, l, w):
self.__length = l
self.__width = w
def getLength(self):
return self.__length
def getWidth(self):
return self.__width
def w... |
# Rank Number
# count 2 rank 5 with ** operator
print(2**5)
# count 2 rank 5 with pow()
print(pow(2,5))
'''
prototype:
pow(x, y[, z]) -> number
when we only put two parameter, this function will only process X ** y
when we put three parameter, then the function will process (x ** y) % z
'''
|
# Reading CSV file
import csv
with open("D:\Rizky's File\Tutorial\Coding\Python\CrashCourse\pencipta.csv", 'r', newline='', encoding='utf-8') as csvfile:
r = csv.reader(csvfile, delimiter=',')
for row in r:
for i in range(len(row)):
print('%s\t'% row[i], end='')
print() # new line
... |
a = [10,20,30,40,50,60]
print(a)
# use del comand
del a[2]
print(a)
# use method remove()
a.remove(20)
print(a)
'''
remove will only delete one value which is in first data
'''
#use method pop()
nilai = a.pop()
print(nilai)
print(a)
'''
pop will only take out the last value
'''
|
# Decrement a Value Function
def decrement(x, value=1):
x = x - value
return x
b = 10
print(decrement(b))
print(decrement(b, 2))
|
# Searching String in certain part
data = ['Akhmad Koysim', 'Akhmad Ilman', 'Anis Yuliana Phasya', 'Rizki Sadewa', 'Muhammad Ilman', 'Muhammad Rozak', 'Muhammad Yusuf']
# Searching the String which is contain the name startwith 'Muhammad'
for name in data:
if name.startswith('Muhammad'):
print(name)
print... |
# function for return a few of value
def getvalues():
return 1, 2, 3
# call the value
a, b, c = getvalues()
print(a)
print(b)
print(c)
'''
getvalues() will return the tuple object,
remember we can also make the tuple without ()
'''
|
# Overloading
class aritmatika:
def tambah(self, *daftarnilai):
total = 0
for i in daftarnilai:
total += 1
return total
# Make an object from class aritmatika
obj = aritmatika()
# call method addition with 2 parameter
print(obj.tambah(2, 3))
# call method addition with 3 para... |
# Editing Dictionary
d = {'one':100, 'two':200, 'three':300}
print(d)
d['two'] = 900
print(d)
'''
Dictionary is sensitive case, especially in key list
'''
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.