text stringlengths 37 1.41M |
|---|
# Write classes for the following class hierarchy:
#
# [Vehicle]->[FlightVehicle]->[Starship]
# | |
# v v
# [GroundVehicle] [Airplane]
# | |
# v v
# [Car] [Motorcycle]
#
# Each class can simply "pass" for its body. The exercise is about setting up
# the hie... |
#Feb 3, lecture
#example: find the smallest integer n such that
#1**3 + 2**3 + 3**3 + ... + n**3 < 10**6
#solution 1: use for loop
s = 0
for i in range(1, 100):
s += i**3
if (s >= 10**6):
print('largest n=', i-1)
s -= i**3
break #this is an important command t... |
'''
fractions_opretions.py
'''
from fractions import Fraction
def add(a, b):
print('Result of adding {0} and {1} is {2}'.format(a, b, a+b))
def substract(a, b):
print('Result of Subtract: {0}'.format(a, b, a-b))
if __name__ == '__main__':
try:
a = Fraction(input('Enter first fraction: '))
... |
# First full line comment of the file
# Second comment of the file
import re # First instruction in block main
print('fgb') # First instruction in main block
print('fghfgh') # Second instruction in the main block
print('dfgdfg') # Now going to the for block, indent 1
for line in content: # First for loop, indent 1
... |
You are given an integer N. You need to print the series of all prime numbers till N.
Input Format
The first and only line of the input contains a single integer N denoting the number till where you need to find the series of prime number.
Output Format
Print the desired output in single line separated by spaces.
... |
n = int(input())
words = set()
for _ in range(n):
words.add(input())
for word in sorted(words, key=lambda x: (len(x), x)):
print(word) |
# Advent of Code 2020
# Day 7, Part 2
# December 13, 2020
def bag_contains(bag_color, bag_cnt):
global rules
global total_bags
global recur_level
outer_bag_cnt = 0
temp_bag_cnt = 0
print('\nLooking for bag colors contained in',bag_cnt,' ',bag_color,'bags:')
for curr_rule in rules:
if (cu... |
# Advent of Code 2020
# Day 1, Part 2
# December 1, 2020
file_name = "day1-input.dat"
with open(file_name) as file_contents:
list1 = file_contents.readlines()
list2 = list1
list3 = list1
for line1 in range(len(list1)):
val1 = int(list1[line1].rstrip())
for line2 in range(len(list2)):
... |
from random import normalvariate, randint
from maxQLearning import QLearningAgent
from matplotlib import pyplot as plt
from numpy import arange
# the actions that the agent will be allowed to perform
actions = ['forward', 'backward', 'stay still']
# the state dimensions
time = arange(-12, 12, 1)
localDemand = arange(... |
from face import Face
class Cubie(object):
"""
Class representing one of the small sub-divisions of the Rubik's cube.
A standard 3x3x3 Rubik's cube has 27 of these.
"""
def __init__(self, matrix):
"""
Initializes a cubie
:param matrix: PMatrix3D placing the cu... |
# Dictionaries in Python
# Key: State
# Value: Capital
statesToCapitals = {}
statesToCapitals["Kansas"] = "Topeka"
statesToCapitals["Arizona"] = "Phoenix"
statesToCapitals["Michigan"] = "Lansing"
# To access values:
print(statesToCapitals["Arizona"])
|
print("Nhập 1 số bất kì lớn hơn 0")
sobatki = int(input(">>>"))
for i in range(sobatki + 1):
print(i) |
from turtle import *
speed(0)
print("Nạp các màu")
mau = input(">>>")
mau = mau.split(",")
for i in mau:
color(i)
forward(30)
mainloop() |
color_list=["red","blue","purple",]
while True:
new_color=input("New color?")
color_list.append(new_color)
print("*"*10)
for color in color_list:
print(color)
print("*"*10) |
print("Nhập họ mày vào")
ho = input(">>>")
print("Nhập tên mày vào")
ten = input(">>>")
print("Tên bạn đã được chuyển thành chữ hoa:", ho.upper(), ten.upper()) |
x = 10
y = 20
z = 100
w = (x + y) * z / 100
print(w)
print("este texto será impresso no console")
print(x)
print("texto e duas variáveis", x, ", ", z)
m = "python"
print("tipo da variável m: ", type(m))
print("tipo da variável x: ", type(x))
print("informe o valor 1:")
i = input()
print(type(i))
var = input("inform... |
import unittest
from check_permutation import check_permutation
class CheckPermutationTest(unittest.TestCase):
def test_is_permutation(self):
self.assertEqual(True, check_permutation("is", "si"))
def test_is_permutation_longer(self):
self.assertEqual(True, check_permutation("aaabbbccc", "abc... |
# Linked list implementation in Python
class Node:
# Creating a node
def __init__(self, item):
self.item = item
self.next = None
class LinkedList:
def __init__(self):
self.head = None
|
def merge_sort(arr):
result = []
# 7
length = len(arr)
if length <= 1:
# print(f'floor of {arr}')
return arr
# 4
mid = length // 2
# print(f'length {length}')
# print(f'mid {mid}')
# 0,1,2,3
left = merge_sort(arr[:mid])
# 4,5,6
right = merge_sort(... |
class Prefix_Tree():
def __init__(self, character=None, level=0, *leaves):
self.character = character
self.leaves = set(leaves)
self.level = level
self.word = ''
def find_words_for_prefix(self, prefix):
current_leaf = self
for character in prefix:
cur... |
class Stack():
def __init__(self):
self.elements = []
self.top = -1
def push(self, element):
self.elements.append(element)
self.top += 1
#print(f'push: {self.top}: {self.elements}')
def pop(self):
if self.top == -1:
return None
element = ... |
primes = []
upto = 100
for n in range(upto + 1):
is_prime = True
for divisor in range(2, n):
if n % divisor == 0:
is_prime = False
break
if is_prime and n > 1:
primes.append(n)
print(primes)
|
a = dict()
b = {}
c = dict(A=1, B=-1)
print(a, b, c)
a.update({'A': 'apple'})
print(a)
a.update(B='banana')
print(a)
a.pop('A')
print(a)
print(a.get('B'))
a.update(A='apple')
print(a)
for key, value in a.items():
print(key, value)
|
import statistics
import random
example_list = [random.randint(1, 100) for i in range(1000000)]
print('list is', example_list)
# mean 平均數
x = statistics.mean(example_list)
print('mean is', x)
# standard Deviation 標準差
y = statistics.stdev(example_list)
print('standard deviation is', y)
# variance 變異數
z = statistics.va... |
late = True
if late:
print('I need to call my manager!')
else:
print('no need to call my manager...')
income = 15000
if income < 10000:
print()
elif income < 20000 and income >= 10000:
print()
else:
print()
# ternary operator
order_total = 247
discount = 25 if order_total > 100 else 0
# errors al... |
num_list = [12,23,2,2,3,1,3,52,44,65,4,12]
fruit_list = ['apple', 'banana', 'cherry']
student_dict = {
'id' : 1,
'name' : 'chris',
}
for i in num_list:
print(i)
for i in range(10):
print(i)
for i in range(1,100,3):
print(i)
for fruit in fruit_list:
print(fruit)
for key in student_dict:
... |
class Solution:
#Function to reverse a linked list.
def reverseList(self, head):
if head is None:
return None
#taking three pointers to store the current, previous and next nodes.
prev = None
current = head
next = current.next
... |
#!/usr/bin/env python2
# Author: Elliot Sayes
# Generates distance to beacons from a given position
import math
x = input("x: ")
y = input("y: ")
X_S = 0;
Y_S = 0;
beacon_locations =[
[X_S+10600, Y_S+1400 ],
[X_S+0, Y_S+2500 ],
[X_S+0, Y_S+2500+12300],
[X_S+10600, Y_S+11400 ]
]... |
#!/usr/bin/env python3
"""
v3 - class
by Richard White https://www.youtube.com/watch?v=wYYzteRKU7U
"""
# Inheritance: Multiple classes than inherit from each other
class Person(object):
"""
The person class defines a person in terms of a name, phone and email)
"""
#Constructor
def __init__(self, theName, thePhone... |
#!/usr/bin/env python3
#
# Print a diff summary like:
#
# $ git diff 'master~10..master' | gn
# 293 lines of diff
# 185 lines (+200, -15)
# 650 words (+10, -660)
#
# or:
#
# $ gn my-awesome-patch.diff
# 293 lines of diff
# 185 lines (+200, -15)
# 650 words (+10, -660)
import fileinput
import os
import ... |
# Import create_engine function
from sqlalchemy import create_engine
# Create an engine to the census database
engine = create_engine("postgresql+psycopg2://student:datacamp@postgresql.csrrinzqubik.us-east-1.rds.amazonaws.com:5432/census")
# Use the .table_names() method on the engine to print the table names
print(e... |
class RadixTree:
def __init__(self):
self.root = self.Node(False)
def insert(self, value):
# We don't permit inserting blank values
if len(value) == 0:
return False
# Start at the root
curr_node = self.root
curr_index = 0
# As long as we have not reached the end of our value, co... |
import os, json
usage = '''
Usage:
python "path_to_this_folder/main.py" [Option]
Option:
-n --new <name> <path>: Create a new shortcut
-o --open <name> [args...]: Open a shortcut with optional arguments
-i --info <name>: View the information of a shortcut
-l --list: View the list of shortcuts
-m --modify [-n --name][... |
# The depth-first search algorithm of maze generation is frequently implemented using backtracking.
# This can be described with a following recursive routine:
#
# 1. Given a current cell as a parameter,
# 2. Mark the current cell as visited
# 3. While the current cell has any unvisited neighbour cells
# 1. Choose on... |
dic = {'k1': 'v1', 'k2': 'v2', 'k3': [11, 22, 33]}
for k in dic:
print(k)
for v in dic.values():
print(v)
for k, v in dic.items():
print(k, ':', v)
dic['k4'] = 'v4'
print(dic)
dic['k1'] = 'alex'
print(dic)
dic['k3'].append(44)
print(dic)
dic['k3'].insert(0, 18)
print(dic)
|
# 编写装饰器,为多个函数加上认证的功能,用户的账号密码来自于文件
# 要求登录成功一次,后续的函数无需再输入用户名和密码
auth = False
def verify(func):
"""
认证,密码来自文件
:return: 是否认证成功
"""
def inner(*args, **kwargs):
global auth
if auth:
ret = func(*args, **kwargs)
return ret
with open('auth', encoding='utf-8... |
dic = {
'name': ['jason', 'tiko'],
'py': {'num': 71, 'age': 18}
}
print(dic.get('name'))
print(dic.get('name')[0])
print(dic.get('py').get('num'))
|
# 写函数,检查传入字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
# 字典中的value只能是字符串或列表
def check_len(dic):
"""
检查传入字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
:param dic: 传入的字典
:return: 保留2个长度的新字典
"""
if isinstance(dic, dict):
for k, v in dic.items():
if isinstance(v, (str, lis... |
pythons = {'alex', 'egon', 'yuanhao', 'wupeiqi', 'gangdan', 'biubiu'}
linuxs = {'wupeiqi', 'oldboy', 'gangdan'}
# 1. 求出即报名python又报名linux课程的学员名字集合
print(pythons.intersection(linuxs))
# 2. 求出所有报名的学生名字集合
print(pythons.union(linuxs))
# 3. 求出只报名python课程的学员名字
print(pythons.difference(linuxs))
# 4. 求出没有同时这两门课程的学员名字集合
pri... |
li = [1, 2, 3, 4]
li2 = list(reversed(li))
print(li2)
si = slice(2, 3)
print(li2[si])
print(format('23', '>20'))
print(bytes('你好', encoding='utf-8'))
print(ord('a'))
print(chr(97))
print('%r' % 'hello world')
print(repr('hello world'))
list1 = ["这", "是", "一个", "测试"]
for index, item in enumerate(list1, 1):
print(ind... |
# 测试一个输入的字符串中,大写字母,小写字母,数字,其他符号的个数
list_upper = []
for i in range(65, 91):
list_upper.append(chr(i))
list_lower = []
for i in range(97, 123):
list_lower.append(chr(i))
list_digit = []
for i in range(48, 58):
list_digit.append(chr(i))
count_upper = 0
count_lower = 0
count_digit = 0
count_other = 0
str_input ... |
# 实现一个整数加法计算器
# 如:content = input(‘请输入内容:’)
# 如用户输入:5+8+7....(最少输入两个数相加),
# 然后进行分割再进行计算,将最后的计算结果添加到此字典中(替换None):
# dic={‘最终计算结果’:None}。
def is_int(number):
for n in number:
if not 48 <= ord(n) <= 57:
return False
else:
return True
def add_int(content):
result = 0
if conte... |
# 注册界面
while True:
print('<--注册界面-->')
username = input('请输入用户名:')
if username:
password = input('请输入密码:')
if password:
password_verify = input('请再次输入密码确认:')
if password == password_verify:
with open('auth', mode='w', encoding='utf-8') as f:
... |
def sum_num(a, b, *args):
"""
求数字的和
:param a: 第一个数字
:param b: 第二个数字
:param args: 更多数字
:return: 所有数字的和
"""
sum_all = a + b
if args:
for i in args:
sum_all += i
return sum_all
print(sum_num(3, 4))
print(sum_num(3, 4, 5))
print(sum_num(3, 4, 5, 6))
|
#Linear Regression with placeholder
#Linear Regression이 뭔지 이전 프로그램에서 알아봤으니 변수바꾸는 placeholder을 사용해보자.
#시작하기 전에 코드를 보자.
import tensorflow as tf
x_data = [1.,2.,3.]
y_data = [1.,2.,3.]
# 기울기 W와 y절편 b를 찾아서 y_data = W * x_data +b를 계산할거야.
# 솔직히 간단해서 우리가 바로 보고 알 수 있지만텐서플로우가 직접 찾게 만들자.
#random uniform의 뜻이 뭐더라?
W = t... |
#/bin/python
#coding: utf-8
#author: ourfor
#date: 20190123
#description: 练习python里面的列表
print("练习Python里面的列表这种数据结构")
test=[1,2,4,8,'a']
print(test[3])
test[3]=test[3]+4
print(test[3])
print(test[0:4:2]) |
def prime():
x = int(input("What is the limit of prime numbers that you want to see?"))
for i in range (2, x+1):
count = 0
for j in range (2, i):
# Made another array so that it can divide the number in the first array too see if it is prime and is
# stops at i because if w... |
from tkinter import *
#import tkinter.messagebox as tmsg
def click(event):
global scvalue
text = event.widget.cget("text")
print(text)
if text == "=":
if scvalue.get().isdigit():
value = int(scvalue.get())
else:
value = eval(screen.get())
scva... |
#dIFFERENCE BETWEEN AN ARRAY ANDA LIST
import numpy as np
x = np.array([1,3,5,7,9])
#divides every value in array by 3
print(x/3)
y = [1,3,5,7,9]
#wont work withought numpy array its not cmputational enough.
print(y/3) |
import sqlite3
from sqlite3 import Error
def create_connection(db_NEA):
""" creates a databse connection to sqlite database by specified db_file """
try:
conn = sqlite3.connect(db_NEA)
return(conn)
except Error as e:
print(e)
return None
def create_table(con... |
#coding=utf-8
# Given a collection of intervals, merge all overlapping intervals.
# For example,
# Given [1,3],[2,6],[8,10],[15,18],
# return [1,6],[8,10],[15,18].
def merge(vs):
if vs==[]:
return vs
vs.sort(key=lambda x:x[0])
new=[]
for i in range(len(vs)-1):
if vs[i][1]<vs[i+1][0]:
new.append(... |
'''
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
For example,
1
/ \
2 3
The root-to-leaf path 1->2 represents the number... |
'''
There are a number of spherical balloons spread in two-dimensional space.
For each balloon, provided input is the start and end coordinates of the horizontal diameter.
Since it's horizontal, y-coordinates don't matter and hence the x-coordinates of start and end of the diameter suffice.
Start is always smaller... |
#
# Given 2 int values, return True if one is negative and one is positive.
# Except if the parameter "negative" is True, then return True only if both are negative.
#
#
# pos_neg(1, -1, False) → True
# pos_neg(-1, 1, False) → True
# pos_neg(-4, -5, True) → True
num1 = int(input('Enter the first num: '))
num2 = int(i... |
import random
while True:
bullet_position = 2
def fire_gun():
camber_position = random.randint(1, 6)
print(camber_position)
if camber_position == bullet_position:
print("you are dead!")
else:
print("keep playing!")
answer = input('Do you want to pl... |
def leap(year):
if year % 4 == 0 and year % 100 != 0 or year % 100 == 0 and year % 400 == 0:
return True
else:
return False
def datefinder(days,year):
months = {'JANUARY':31, 'FEBRUARY':28, 'MARCH':31, 'APRIL':30, 'MAY':31, 'JUNE':30, 'JULY':31, 'AUGUST':31, 'SEPTEMBER':30, 'OCTOBER'... |
def bin(n):
#generate binary
res = ''
n = int(n)
while n:
r = n%2
res = res + str(r)
n = n//2
return res[::-1]
n = input('INPUT: ')
if int(n) > 100:
print('OUT OF RANGE')
exit()
binary = bin(n)
print(f'BINARY EQUIVALENT: {binary}',f"NUMBER OF 1's... |
sent = input('')
if sent[-1] not in '?.!':
print('Invalid Input')
exit()
op =''
input('WORD TO BE DELETED: ')
dpos = int(input('WORD POSITION IN THE SENTENCE: '))
for k, word in enumerate(sent.split(), start=1):
word.strip()
if k == dpos:
pass
else:
op = op + word ... |
def prime(num):
for i in range(2, num):
if num % i == 0:
return False
return True
m = int(input('M = '))
n = int(input('N = '))
if not 0 < m < 3000 or not 0 < n < 3000 or m > n:
print('INVALID/OUT OF RANGE')
exit()
pnum_lis = []
for num in range(m, n +1):
if... |
# import turtle
# name = input("What is your name?")
# print("Hello, " + name + "!")
# turtle.speed(5)
# turtle.goto(0,0)
# for i in range(4):
# turtle.forward(100)
# turtle.right(100)
# turtle.home()
# turtle.circle(50,270) # turtle包在python3可能不兼容
# 打印圆的周长: (注释)
pi = 3.14
radius = 6
print(2 * pi * radius)
... |
import math, pylab, scipy, numpy
g = 9.81 # acceleration
ax = 0 # acceleration from x
ay = -9.81 # acceleration from y
v0 = 30.0 # initial velocity
angle = 30.0 # launch angle (degrees)
dt= numpy.arange(0,5,0.001) # time intervalle
pylab.xlim(0,80)
pylab.ylim(0,12)
old_dx = 0.0 # displacement dx (X-axis) at the i... |
def say_hello():
# block belonging to the function
print('hello world')
# end of function
say_hello() # call the function
#say_hello() # call the function again
# New function from here
def print_max(a, b):
if a > b:
print(a, 'is maximu')
elif a == b:
print(a, 'is equal to', b)
... |
class SchoolMember:
'''Represent any school member'''
def __int__(self,name,age): #What does __init__ do ????
self.name = name
self.age = age
print('(Initializing schoolMember: {})'.format(self.name))
def tell(self):
'''Tell my details'''
print('Name: "{}" Age: "{}"'... |
def and_(a,b,c):
result=list()
if (a and b)==c:result.append("AND")
if(a or b)==c:result.append("OR")
if(a != b)==c:result.append("XOR")
return result
def print_(rel):
if len(rel)==0:
print("IMPOSSIBLE")
return
for x in range(len(rel)):print(rel[x])
return
keyin=list(map(int,input().... |
while True:
# > The problem requires multiple test materials.
try:i,j=map(int,input().split())
# > i,j is the range of data entered by user.
except:break
# > Stop the program when the input is over.
def lenghgenerater(n,step):
while True:
# > start to ... |
def kioro (num):#判斷奇數偶數
if(num%2)==0:return 1
else:return 0
def count_(num):#計算3n+1的次數
len_=0
while num!=1:
if(kioro(num)==0):
num=num*3+1
len_+=1
else:
num=num//2
len_+=1
return len_+1
def findmax(x,y):#取得數據之中的計算結果的最大值
print(x,y,end=" ")
if x>y:x,y=y,x
ma... |
#-#-# Question 2 -: write a Program Using for loop to print prime nos between 1-1000. #-#-#
# HEy I am using Pycharm IDE
print("Prime Number between 1-1000 are -: ")
for num in range(1,1000 + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
... |
#Try 5 different functions of Lists in python ?
# Hey! I am using the PyCharm Editor for Python coding
print("Functions of List")
Lst=["Saurabh","Pawar",1,2,3,1.2,1.3,["Daund",1,1.2],44]
#Accessing the last element of list
print(Lst[-1])
#Getting the position of specific element
print(Lst.count("Pawar"))... |
# Assignment 5: Implement Heapsort and Quicksort accordingly.
# Pranpreya Samasutthi (st122602)
import math
from random import randint
random_list = []
def build_max_heap(arr):
half_to_root = math.ceil(len(arr)/2)
for i in range(half_to_root-1, -1, -1):
max_heapify(arr, len(arr), i)
... |
def prime_factorize(n):
a = []
while n % 2 == 0:
a.append(2)
n //= 2
f = 3
while f * f <= n:
if n % f == 0:
a.append(f)
n //= f
else:
f += 2
if n != 1:
a.append(n)
return a
# import numpy as np
t = int(input())
ans = []
... |
n = int(input())
ans = 'Bad'
if n == 100:
ans = 'Perfect'
elif 90 <= n:
ans = 'Great'
elif 60 <= n:
ans = 'Good'
print(ans)
|
import sys
while True :
n_time = []
c = ''
time = raw_input('Type the time in the format"hh:mm:ss(AM/PM)":\n').strip()
for i in time:
if (not i.isdigit()) and (not i == ':'):
n_time.append(i)
t = ''.join(n_time)
while int(time[0:2]) > 12:
print "Something ... |
import matplotlib
import matplotlib.pyplot as plt
import csv
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
def graph():
with open("monte-carlo-liberal.csv") as montecarlo:
data = csv.reader(montecarlo, delimiter=',') # Easily read contents from csv f... |
import sys
import random #only for random_bot
#player switcher
def player_switcher(cp):
if cp == "X":
return("O")
elif cp == "O":
return("X")
else:
return(None)
#starting variables
current_player = "X"
win = 0
winner = "temp"
free_spots = [1,2,3,4,5,6,7,8,9]
starting_field = ["1","2","3","4","5","6","7","8",... |
"""
Strategy class with all implemented strategies
"""
import random
def closest_pos(pos):
"""
Return figure that is closest to home
"""
completed_board_list = [] # figures that completed board, but aren't finished yet
closest_list = []
closest = None
# pylint:disable=invalid-name
... |
#PASSWORD GENERATOR
from numpy import random
set_alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
set_upper_alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U... |
# For Testing:
# Naive solution for generating the Recamann sequence
# Put numbers into a dict as they are generated
import sys
def main(end):
n = 0
database = {}
while jump < end:
key = n - jump
if key in database or key < 0:
n = n + jump
else:
... |
import sys
import os
from PIL import Image
#grab first and second argument with the image's paths arguments in sys would be JPGtoPNGconverter.py [0] Pokedex/ [1] new/ [2]
#which means that the terminal comand will be: python3 JPGtoPNGconverter.py Pokedex/ New/
image_folder = sys.argv[1]
output_folder = sys.argv[2]
#... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 27 20:14:29 2019
@author: tylersschwartz
"""
def get_start_balance():
"""Requests the user's current loan balance, returns an int."""
while True:
try:
balance = int(input("Enter your starting balance: "))
if b... |
# ================================================== Hash Functions =================================================
def hash_string_unweighted(astring, table_size):
"""Simple Hash Function for Strings."""
temp = 0
for pos in range(len(astring)):
temp = temp + ord(astring[pos])
print(f'The v... |
# first_numbers
# for value in range(6):
# print(value)
# numbers = list(range(1, 6))
# print(numbers)
# Even Numbers
# even_numbers = list(range(2,11,2))
# print(even_numbers)
# functions with numbers
# digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
# print(min(digits))
# print(max(digits))
# print(sum... |
S=input()
res=""
lens=len(S)
while(lens>0):
rev=S[lens-1]
lens-=1
res=res+rev
if S==res:
print("YES")
else:
print("NO") |
print("This is another test")
ans = input("Is this working")
if ans=="yes":
print("okay cool")
else:
print("oh, too bad :(")
|
file1=open("file1.txt",'r')
file1_content=file1.readlines()
file1.close()
file2=open('file2.txt','r')
file2_content=file2.readlines()
file2.close()
result_file=open('file3.txt','w')
class Fileloop :
def __init__(self,file1,file2):
self.file1=file1
self.file2=file2
def __iter__(self):
... |
from datetime import date as d
name=""
age=""
while name=="":
name=input("\nEnter name :\t")
while age=="":
age=input("\nEnter age:\t")
try:
age=int(age)
except:
print("\nenter valid integer")
age=""
continue
def calcAge(uage):
today=d.today()
diff=100-uage
return today.year+diff
pri... |
# sixth chapter
# function
# bank
def open_account():
print("New account is created.")
def deposit(balance, money):
print("deposit completed. your balance : {0}".format(balance + money))
return balance + money
def withdraw(balance, money):
if balance >= money:
print("withdraw completed. your ... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 30 01:11:39 2020
@author: berka
"""
from rent_a_vehicle import CarRent, BikeRent, Customer
bike = BikeRent(100)
car = CarRent(25)
customer = Customer()
main_menu = True
while True:
if main_menu:
print("""
***** Vehicle Rental Sh... |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 8 19:01:48 2019
@author: berka
"""
"""
OOP : Object Oriented Programming
: class / object/constructor
: attirubutes / methods
: encapsulation / abstraction
: inheritance
: overriding / polymorphism
"""
from abc import ABC, abstractmethod # import ab... |
__author__ = 'rsimpson'
"""
I started with minimax code that I found here:
http://callmesaint.com/python-minimax-tutorial/
That code was written by Matthew Griffin
Then I added in code I got from here:
https://inventwithpython.com/tictactoe.py
That code was written by Al Sweigart
Then I started adding my own code
"... |
#!/usr/bin/python
import time, random
def merge(a, start1, start2, end):
index1 = start1
index2 = start2
'''length is the total length of two groups of number'''
length = end - start1
aux = [None] * length
for i in range(length):
'''two groups compare,merge to aux'''
if ((index1 == start2) or
'''if first g... |
#!/usr/bin/env python3
#-*- coding:UTF-8 -*-
class result(object):
wheatNum = 0
wheatTotalNum = 0
class getWheatTotalNum(object):
'''
函数说明:使用递归嵌套, 进行数学归纳法证明
Param: k - 表示放到第几格 result - 表示当前格子的麦粒数
Return: boolean - 放到第K格时是否成立
'''
def prove(self, k, result):
if k == 1:
if (2 ** 1 - 1) == 1:
... |
N = int(input())
myList = list()
for i in range(N):
cmd = input().split()
if cmd[0] == "append":
myList.append(int(cmd[1]))
elif cmd[0] == "insert":
myList.insert(int(cmd[1]),int(cmd[2]))
elif cmd[0] == "remove":
myList.remove(int(cmd[1]))
elif cmd[0] == "pop":
myLi... |
import requests
from decimal import Decimal
def get_eurusd():
""" Return the current EUR/USD exchange rate from Yahho Finance API.
:return: Current EUR/USD exchange rate
"""
# See:
# http://code.google.com/p/yahoo-finance-managed/wiki/csvQuotesDownload
# http://code.google.com/p/yahoo-... |
mylist = [2,1,4,5,9,12,45]
print map(str,mylist) # ['2', '1', '4', '5', '9', '12', '45']
#---------------
names = ['Anne', 'Amy', 'Bob', 'David', 'Carrie', 'Barbara', 'Zach']
lengths = map(len, names)
print lengths # [4, 3, 3, 5, 6, 7, 4]
#--------------------
# lambda usage
print (lambda x, y: x*y)(3, 4) # 12
# ... |
# In the following situation diamond problem is the order in which the call() is taken
# Initially it will taken as B2,B1,B3 and if we restuctures it will take as itsown
class A:
def call(self):
pass
class B1(A):
def call(self):
print "I am parent B1"
class B2(A):
def call(self):
print "I am pare... |
# SOlution for the problem no-6
# Program to find the difference between the sum of the squares
# of the first ten natural numbers and the square of the sum
import logging
def diff_sumsquare(max):
N = int(max)
sum1, sum2 = 0, 0
for i in range(1, N + 1):
sum1 += i
sum2 += pow(i,2)
return pow(sum1,2) ... |
__author__ = 'Student'
#lab 5 opdracht 2: (the infamous) Scrambled Eggs
#samenvatting: het gebruiken van een array binnen een forloop in een functie
#onze pseudocode om te beginnen:
#een nieuwe functie die def Scramble heet met 2 parameters (woord1 en woord2)
#een nieuwe variable maken voor het gescramble woord
... |
class Car(object):
def __init__(self, x,y,w,h,xSpeed,ySpeed,rotSpeed):
self.x = x
self.y = y
self.w = w
self.h =h
self.xSpeed =xSpeed
self.ySpeed =ySpeed
self.rotSpeed = rotSpeed
self.angle = 0
def update(self):
pushMatrix()
... |
def key_assign(key):
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key_list = list(range(len(key)))
#print all in list to check
key_num = 0
for row in range(len(alphabet)):
for column in range(len(key)):
if alphabet[row] == key[column]:
key_num += 1
key... |
#You are given two sequences. Write a program to determine the longest common subsequence between the two
# strings (each string can have a maximum length of 50 characters). NOTE: This subsequence need not be
# contiguous. The input file may contain empty lines, these need to be ignored.
#The first argument will be a ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.