text stringlengths 37 1.41M |
|---|
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 29 21:09:19 2018
@author: 程甜甜
"""
def merge_sort(array):
if len(array) <= 1:
return array
num = int(len(array)//2)
left = merge_sort(array[:num])
right = merge_sort(array[num:])
return merge(left,right)
def merge(left,right):
l,r = 0,0
... |
def binSearch(lst, item):
mid = len(lst) //2
found = False
if lst[mid] ==
item:
found = True
return found
if mid == 0:
#mid0ҵһԪˡ
found = False
return found
else:
if item > lst[mid]: #Һ벿
#print(lst[mid:])
return
binSearch(lst[mid:], item)
else:
return
binSearch(lst[:mid], ite... |
def merge(left, right):
res = []
while left and right:
if left[0] < right[0]:
res.append(left.pop(0))
else:
res.append(right.pop(0))
res = res + left + right
return res
def mergesort(lists):
if len(lists) <= 1:
return lists
mid = len(lists)//2
... |
def selection_sort(alist):
for i in range(0, len (alist)):
min = i
for j in range(i + 1, len(alist)):
if alist[j] < alist[min]:
min = j
alist[i], alist[min] = alist[min], alist[i]
return alist
alist = [4,2,5,7,21,3,14,35,23]
print(selection_sort(alist))
|
#QuickSort by Alvin
def QuickSort(myList,start,end):
#判断low是否小于high,如果为false,直接返回
if start < end:
i,j = start,end
#设置基准数
base = myList[i]
while i < j:
#如果列表后边的数,比基准数大或相等,则前移一位直到有比基准数小的数出现
while (i < j) and (myList[j] >= base):
j = j - 1
... |
def QuickSort(myList,low,high):
i,j = low,high
if i >= j:
return
base = myList[i]
while( i<j ):
while (i < j) and (myList[j] >= base):
j = j - 1
myList[i] = myList[j]
while (i < j) and (myList[i] <= base):
i = i + 1
myList[j] = myList[i]
m... |
even_numbers = [x for x in range(1,101) if x % 2 ==0]
print (even_numbers)
odd_numbers = [x for x in range(1,101) if x % 2 != 0]
print (odd_numbers)
|
#list
l1=[12,4,12,45,223,7,"a","s",True]
print (l1)
print (type(l1))
print (l1[4])
print (l1[-1])
name = l1[-2]
print (name)
#list[start:end:step]
print (l1[0:3])
l2 = [1,2,3,4,[5,6,7,],8,9,0]
print (l2)
print (l2[4])
print (l2[4][1])# it print the inner list 1 st position
print (l2[4][1:])# it print the inner list 1... |
#input from user
name = input("enter your name: ")
age = int(input("enter your age :"))
loc = input("enter your location :")
pin = input("enter your pin code :")
data ="your name is {} , your age is {} , your location is {} , your pincode is {}"
output=data.format(name,age,loc,pin)
print (output)
# below exampl... |
import random
from kivy.app import App
from action import Action
NONE = 0
S = 1
O = 2
class Turn:
"""
The class for turns
"""
def __init__(self, num):
"""
The constructor
:param num: Turn number in the game
"""
self.choice = NONE
self.done = False
... |
from scipy.stats import norm
import matplotlib.pyplot as plt
import numpy as np
variable = norm.rvs(size=1000)
# Fit a normal distribution to the data:
mu, std = norm.fit(variable)
# Plot the histogram.
plt.hist(variable, bins=25, normed=True, color='g')
# Plot the PDF.
xmin, xmax = plt.xlim()
x = np.linspace(xmin,... |
# Write a Python program to print the even numbers from a given list. Go to the editor
def even(list):
i=0
while i<len(list):
if list[i]%2==0:
print("EVEN NUMBER - ", list[i])
i+=1
even([2,3,4,5,6,7]) |
from functools import *
def anymap(func, l, x):
""" check if func(x, y) for any y in l is true
"""
return any(map(partial(func, x), l))
def allmap(func, l, x):
""" check if func(x, y) for all y in l is true
"""
return all(map(partial(func, x), l))
def filteranymap(func, l1, l2):
""" Se... |
def hadron_collider_mt2(p1, p2):
"""Computes the transverse mass in two-particle system.
Parameters
----------
p1 : TLorentzVector
The first particle
p2 : TLorentzVector
The second particle
Returns
-------
The transverse mass of the two-particle system as defined in [1]... |
""" Napišite program koji s tipkovnice učitava tri cijela broja: redni broj
dana u mjesecu, redni broj mjeseca u godini i redni broj godine.
Prekontrolirajte jesu li učitane vrijednosti ispravne (ispravne
vrijednosti su: dan - [1, 31], mjesec - [1, 12], godina - [0, 2020]). Za
ulazne podatke 19, 2, 2017, ispišite ... |
""" Napišite program koji sadrži varijablu u kojoj je upisan proizvoljni
niz znakova i varijablu n. Provjerite da li je vrijednost varijable n
manja od broja znakova u nizu. Ako je vrijednost varijable n veća
ispišite informaciju o grešci. Ispišite iz niza znakova svako n-to
slovo. Na primjer, ulazni niz je "ABCDE... |
""" Napišite program koji će inicijalizirati u varijablu proizvoljnog imena,
proizvoljnu vrijednost temperature izražene u stupnjevima
Celzijevim. Na ekran ispisati vrijednost temperature u farenhajtima.
Formula: ( 𝑥 × 9/5) + 32 , x je vrijednost izražena u stupnjevima
Celzijevim. """
celz = input("Unesi temp... |
""" U službenoj Python 3 dokumentaciji pronađite ime funkcije za
potenciranje (zamjena za aritmetički operator **). S tipkovnice
učitajte cjelobrojne vrijednosti i spremite ih u varijable a i b. Nije
potrebno provjeravati ispravnost učitanih brojeva. Na temelju tih
vrijednosti izračunajte kvadrat zbroja (𝑎 + 𝑏)*... |
""" Napišite program koji će inicijalizirati u varijable a i b dva broja
proizvoljnih vrijednosti. Ako je vrijednost varijable a bar za 50 veća
od vrijednosti varijable b, a uz to je vrijednost varijable b parna, tada
ispišite poruku "Uvjeti su zadovoljeni.", u suprotnom ispišite poruku
"Uvjeti nisu zadovoljeni. ""... |
"""
给定一棵二叉树,其中每个节点都含有一个整数数值(该值或正或负)。设计一个算法,打印节点数值总和等于某个给定值的所有路径的数量。注意,路径不一定非得从二叉树的根节点或叶节点开始或结束,但是其方向必须向下(只能从父节点指向子节点方向)。
示例:
给定如下二叉树,以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
3
解释:和为 22 的路径有:[5,4,11,2], [5,... |
# 写一个函数,输入 n ,求斐波那契(Fibonacci)数列的第 n 项。斐波那契数列的定义如下:
#
# F(0) = 0, F(1) = 1
# F(N) = F(N - 1) + F(N - 2), 其中 N > 1.
#
# 斐波那契数列由 0 和 1 开始,之后的斐波那契数就是由之前的两数相加而得出。
#
# 答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。
#
#
#
# 示例 1:
#
# 输入:n = 2
# 输出:1
#
#
# 示例 2:
#
# 输入:n = 5
# 输出:5
#
#
#
#... |
"""
You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
Example:
Input: (7 -> 1 -> 6) + (5 -> 9 -> 2).... |
# 森林中,每个兔子都有颜色。其中一些兔子(可能是全部)告诉你还有多少其他的兔子和自己有相同的颜色。我们将这些回答放在 answers 数组里。
#
# 返回森林中兔子的最少数量。
#
#
# 示例:
# 输入: answers = [1, 1, 2]
# 输出: 5
# 解释:
# 两只回答了 "1" 的兔子可能有相同的颜色,设为红色。
# 之后回答了 "2" 的兔子不会是红色,否则他们的回答会相互矛盾。
# 设回答了 "2" 的兔子为蓝色。
# 此外,森林中还应有另外 2 只蓝色兔子的回答没有包含在数组中。
# 因此森林中兔子的最少数量是 5: 3 只回答的和 2 只没有回答的。
#
# 输入: answers ... |
# 冬季已经来临。 你的任务是设计一个有固定加热半径的供暖器向所有房屋供暖。
#
# 现在,给出位于一条水平线上的房屋和供暖器的位置,找到可以覆盖所有房屋的最小加热半径。
#
# 所以,你的输入将会是房屋和供暖器的位置。你将输出供暖器的最小加热半径。
#
# 说明:
#
#
# 给出的房屋和供暖器的数目是非负数且不会超过 25000。
# 给出的房屋和供暖器的位置均是非负数且不会超过10^9。
# 只要房屋位于供暖器的半径内(包括在边缘上),它就可以得到供暖。
# 所有供暖器都遵循你的半径标准,加热的半径也一样。
#
#
# 示例 1:
#
#
# 输入: [1,2,3],[... |
# 给定一个单链表,随机选择链表的一个节点,并返回相应的节点值。保证每个节点被选的概率一样。
#
# 进阶:
# 如果链表十分大且长度未知,如何解决这个问题?你能否使用常数级空间复杂度实现?
#
# 示例:
#
#
# // 初始化一个单链表 [1,2,3].
# ListNode head = new ListNode(1);
# head.next = new ListNode(2);
# head.next.next = new ListNode(3);
# Solution solution = new Solution(head);
#
# // getRandom()方法应随机返回1,2,3中的一... |
# 给你一个混合了数字和字母的字符串 s,其中的字母均为小写英文字母。
#
# 请你将该字符串重新格式化,使得任意两个相邻字符的类型都不同。也就是说,字母后面应该跟着数字,而数字后面应该跟着字母。
#
# 请你返回 重新格式化后 的字符串;如果无法按要求重新格式化,则返回一个 空字符串 。
#
#
#
# 示例 1:
#
# 输入:s = "a0b1c2"
# 输出:"0a1b2c"
# 解释:"0a1b2c" 中任意两个相邻字符的类型都不同。 "a0b1c2", "0a1b2c", "0c2a1b" 也是满足题目要求的答案。
#
#
# 示例 2:
#
# 输入:s = "leetcod... |
# 给你一个字符串 s ,字符串的「能量」定义为:只包含一种字符的最长非空子字符串的长度。
#
# 请你返回字符串的能量。
#
#
#
# 示例 1:
#
# 输入:s = "leetcode"
# 输出:2
# 解释:子字符串 "ee" 长度为 2 ,只包含字符 'e' 。
#
#
# 示例 2:
#
# 输入:s = "abbcccddddeeeeedcba"
# 输出:5
# 解释:子字符串 "eeeee" 长度为 5 ,只包含字符 'e' 。
#
#
# 示例 3:
#
# 输入:s = "triplepillooooow"
# 输出:5
#
#
# 示例 4:
... |
# 搜索旋转数组。给定一个排序后的数组,包含n个整数,但这个数组已被旋转过很多次了,次数不详。请编写代码找出数组中的某个元素,假设数组元素原先是按升序排列的。若
# 有多个相同元素,返回索引值最小的一个。
#
# 示例1:
#
# 输入: arr = [15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14], target = 5
# 输出: 8(元素5在该数组中的索引)
#
#
# 示例2:
#
# 输入:arr = [15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14], target = 11
# 输出:-1 (没有找到)
#
... |
# 给定两个字符串 s 和 t,它们只包含小写字母。
#
# 字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
#
# 请找出在 t 中被添加的字母。
#
#
#
# 示例:
#
# 输入:
# s = "abcd"
# t = "abcde"
#
# 输出:
# e
#
# 解释:
# 'e' 是那个被添加的字母。
#
# Related Topics 位运算 哈希表
# leetcode submit region begin(Prohibit modification and deletion)
class Solution(object):
def find... |
# 括号。设计一种算法,打印n对括号的所有合法的(例如,开闭一一对应)组合。
#
# 说明:解集不能包含重复的子集。
#
# 例如,给出 n = 3,生成结果为:
#
#
# [
# "((()))",
# "(()())",
# "(())()",
# "()(())",
# "()()()"
# ]
#
# Related Topics 字符串 回溯算法
# leetcode submit region begin(Prohibit modification and deletion)
class Solution(object):
def generateParenth... |
"""
Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 (e.g.,"waterbottle" is a rotation of"erbottlewat"). Can you use only one call to the method that checks if one word is a substring of another?
Example 1:
Input: s1 = "waterbottle", s2 = "erbottlewat"
Output: True
Example 2:
Input: s1 = "... |
# 给你一棵以 root 为根的二叉树和一个 head 为第一个节点的链表。
#
# 如果在二叉树中,存在一条一直向下的路径,且每个点的数值恰好一一对应以 head 为首的链表中每个节点的值,那么请你返回 True ,否则返回 False
# 。
#
# 一直向下的路径的意思是:从树中某个节点开始,一直连续向下的路径。
#
#
#
# 示例 1:
#
#
#
# 输入:head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null
# ,1,3]
# 输出:true
# 解释:树中蓝色的节点构成了与链表对应的子... |
import textwrap
a = 'ABCDEFGHIJKLIMNOQRSTUVWXYZ'
b = 'ABCDCDC'
def count_substring(string, sub_string):
count = 0
sub_len = len(sub_string)
for i in range(len(string)):
if i+sub_len <= len(string):
if (string[i:i+sub_len])==sub_string:
count+=1
return count
def abc... |
"""
银行系统
"""
import random
import time
# 存储卡信息
class Card(object):
def __init__(self, cardId, cardPasswd, cardMoney):
self.cardId = cardId
self.cardPasswd = cardPasswd
self.cardMony = cardMoney
self.cardLock = False # 后面到了锁卡的时候需要有个卡的状态
# 存储用户信息
class User(object):
def __init... |
"""
a) 每次增加pay值时,根据用户的付费渠道信息,计算real_pay增加值=pay增加值×渠道系数(渠道系数可配置)
b) 用户价值=real_pay+(outcome- income)-(exchangeincome)-cpl奖励(cpl_reward)
"""
# 计算充值后的real_pay
def calculate_real_pay():
pay = float(input("请输入充值数:"))
proportion = float(input("请输入渠道系数:"))
now_real_pay = float(input("请输入现在real_pay的值:"))
add_... |
def gen_matrix(d):
# 用二维数组来代表矩阵
hh = int(d)
matrix = [[0 for col in range(hh)] for row in range(hh)]
return matrix
def get_rota_matrix(d):
mat = gen_matrix(d) # 初始矩阵,所有元素都为0
x = y = 0
total = mat[x][y] = 1 # 将数组第一个元素设为1,即mat[0][0] = 1
while total != d * d:
while y + 1 < d and ... |
a=input()
cnt = 0
board = [[0]*9 for i in range(9)]
for j in range(9):
for k in range(9):
x = j//3*3 + k//3
y = j%3*3 + k%3
# print(j,k,x,y)
board[x][y] = cnt
cnt += 1
for j in range(9):
for k in range(9):
print("%2d"%board[j][k], end=' ')
print()
|
# 소수체크
import math
def isPrime(N):
for i in range(2, N):
if N % i == 0:
return False
# if i >= math.sqrt(N): # 시간 복잡도를 O(N) > O(루트N)
if i*i > N:
break
return True
assert isPrime(331)
assert isPrime(19)
# 소인수분해 (조금 까다롭..)
def prime_factorization(N):
p,... |
import termcolor2
m = int(input())
n = int(input())
for _ in range(0 , n):
if _ % 2 == 0:
for _ in range(0 , m):
if _ % 2 == 0:
print(termcolor2.colored("$", color="yellow") , end=' ')
elif _ % 2 == 1:
print(termcolor2.colored("@", color="r... |
num1 = int(input())
num2 = int(input())
print('PROD = {:d}'.format((num1*num2))) |
#June Jeongwon Seo
#2016-05-31
#Homework3
#LISTS
#1
countries = ['South Korea', 'North Korea', 'Australia', 'Greece', 'Costa Rica', 'Mexico', 'Japan']
#2
for lala in countries:
print (lala)
#3
countries = ['South Korea', 'North Korea', 'Australia', 'Greece', 'Costa Rica', 'Mexico', 'Japan']
print('-----------SO... |
def part_1():
numSteps = 0
instructions = []
#load instructions
input = open("inputs/day5.txt", "r")
for line in input:
instructions.append(int(line.strip()))
input.close()
i = 0
while True:
j = instructions[i]
instructions[i] += 1
i += j
numSteps... |
from collections import Counter
def noDuplicates(phrase):
words = phrase.split()
counts = list(Counter(words))
return len(words) == len(counts)
def noAnagrams(phrase):
words = phrase.split()
counts = [Counter(w) for w in words]
unique = [c for n, c in enumerate(counts) if c not in counts[n+1:]... |
# Robot Programming
# breadth first search
# by Dr. Qin Chen
# May, 2016
import sys
import Tkinter as tk
##############
# This class supports display of a grid graph. The node location on canvas
# is included as a data field of the graph, graph.node_display_locations.
##############
class GridGraphDisplay(object):
... |
def count_consonants(str):
str_lower=str.lower()
consonants="bcdfghjklmnpqrstvwxz"
count=0
for x in str_lower:
for y in consonants:
if x == y:
count+=1
else:
pass
return count
print(count_consonants("A nice day to code!")) |
from bill import Bill
class BillBatch:
def __init__(self, batch):
if type(batch) != list:
raise TypeError('Invalid argument given, argument needs to be of type list!')
else:
for bill in batch:
if type(bill) != Bill:
raise TypeError('Inval... |
import constants
class Pond():
def __init__(self, leftside_frogs_number, rightside_frogs_number):
assert leftside_frogs_number >= 0 and rightside_frogs_number >= 0, 'Enter non-negative number of frogs per side'
self.leftside_frogs_number = leftside_frogs_number
self.rightside_frogs_number ... |
import unittest
from sort_array_of_fractions import sort_fractions
class TestSortFractions(unittest.TestCase):
def test_with_given_non_list_of_fractions_should_raise_exception(self):
fractions = None
exc = None
try:
result = sort_fractions(fractions)
except Exception as e:
exc = e
self.assertIsNotNo... |
from players import Player, Computer
from random import shuffle
def game():
player_name = input('Enter your name to start the game: ').strip()
while len(player_name) == 0:
player_name = input('Enter your name to start the game, please: ').strip()
player = Player(player_name)
computer = Comput... |
def shellsort(data, length):
gap = length//2
while gap > 0:
for index in range(gap, length):
temp = data[index]
index2 = index
while index2 >= gap and data[index2 - gap] > temp:
data[index2] = data[index2 - gap]
index2 -= ... |
height = float(input("input height: "))
wieght = float(input("input wieght: "))
def bmi(wieght,height):
work_bmi = wieght/(height**2)
opt_weight = optimalweight(height)
print(f"your optimal weight is {opt_weight}")
check_overweight(work_bmi)
return work_bmi
def check_overweight(bmi):
if bmi < ... |
print("What's your name")
name = input ()
if name == "Zach":
print("Welcome back!")
else:
print("Hello " + name)
print("What's your favorite sport?")
sport = input ()
if sport == "Football":
print("That's my favorite too!")
elif sport == "soccer":
print("I love playing soccer too.")
... |
#! /usr/bin/env python
# -*- coding=utf8 -*-
'''
处理快递单号
'''
def readCSV1(filename):
f = open(filename, 'r')
deliver_nos = []
deliver_info = {}
for line in f.read().split('\n')[:-1]:
items = line.split(',')
#print items[7],"宅急送"
if items[7] == '宅急送':
#print items[7]
... |
import re
def check(s):
s = s.lower()
str = re.findall("[a-zA-Z0-9]", s)
rstr = str[::-1]
print(str)
print(rstr)
if str == rstr:
return True
else:
return False
print (check("ab2a"))
|
import unittest
import application.validator as validator
class ValidatorTestCase(unittest.TestCase):
def test_date_formatting(self):
# date should be changed to format 'YYYY-MM-DD'
provided = '2010-2-1'
expected = '2010-02-01'
self.assertEqual(validator.get_string_date_fr... |
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Any
class Handler(ABC):
"""
Represents an interface that declares a method for building a chain of handlers,
otherwise known as the chain of responsibility pattern.
It also declares a method for executing a requ... |
#This program was designed by Adam Cox on 7/4/2019 it has two turtles race on screen.
import random
import turtle
def cords(x,y): #Needs to run multiple times as they might collide at various points
a,b=x.pos()
c,d=y.pos()
style = ("Arial", 15)
equal=False
if(a==c) and (c==d):
x.write("Draw... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
rand_num = random.randrange(10)
for i in range(3):
guess_num = int(raw_input('请猜猜数字: '))
if guess_num == rand_num:
print '太棒了,猜对了'
break
elif guess_num > rand_num:
print '你猜测的数字有对大了,请尝试小点的数字'
else:
print '你猜测的数字... |
from ConvexPolygon import ConvexPolygon
import Descryptors as desc
import math
class Triangle(ConvexPolygon):
fill_colour = desc.ColorV()
outline_colour = desc.ColorV()
length_of_a = desc.SideV()
length_of_b = desc.SideV()
length_of_c = desc.SideV()
def __init__(self, fill_colou... |
# Compute the lowest common ancestor for a binary tree for two given nodes
###### CONDITION ########:
# Assuming that both the ndoes are present in the tree
def lca(root, n1, n2):
# Recursive approach
# The function tries to return the pointer to the lca
# Base case:
if root == None:
return Non... |
# LinkedIn Phone Interview
# Given a binary search tree and a target value, find k values in the binary search tree (BST) that are closest to the target.
#
# Given the following Binary Search Tree:
# 10
# / \
# 5 20
# /\ /\
# 1 6 15 30
# ... |
books = "title,autor,1,r"
book = books.split(",")
print(book)
print(book[0])
print(len(book))
string = "new book"
books.insert(0, string)
print(books) |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import numpy as np
#下标 0,1,2
li = [1,2,3]
print(li[1])
print('------------------------------------')
#数组索引
#一维数组索引
arr = np.array([1,2,3])
print(arr[1])
#二维的索引
arr = np.array([np.arange(1,4),np.arange(4,7)])
print(arr)
#筛选二维数组时,下标[行,列]
print(arr[0,1])
print(arr[1,2])
print(a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from os import walk
import icons
import objects
import print_types
def choose_level():
level = []
while not is_valid_level(level):
levels = load_levels_from_files()
print_levels(levels[:])
player_input = input("Choose: ")
if player_in... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def dbsearch(db, key_value, search_value):
return_list = []
for person in db:
if search_value in person[key_value]:
return_list.append(person)
return return_list
def TEST():
return [
{'name': 'Jakob', 'position': 'assistant'},
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from functools import reduce
def uppg_1_2(num):
add_val = lambda x, y: x + y
mult_val = lambda x, y: x * y
function_list = [add_val, mult_val]
return_list = []
for function in function_list:
return_list.append(reduce(function, range(1, num+1)))
... |
### Copyright Fabian Blank
### In this chapter we will build a math trainer
import random
from decimal import Decimal, getcontext
getcontext().prec = 2
def trainMath (iterations, min, max, isTest):
### You will get the following variables
### iterations - number of questions
### min - minimum number... |
### Copyright Fabian Blank
from functions import doubleNumber, rootDouble
def testDoubleNumber0():
assert doubleNumber(0) == 0, 'Learn maths'
def testDoubleNumber1():
assert doubleNumber(15) == 30, 'Learn maths'
def testDoubleNumber2():
assert doubleNumber(8888888888) == 17777777776, 'Are... |
class myClass:
def __init__(self, inp):
self.inp=inp
def getString(self):
self.inp=input("Give input\n")
def printString(self):
print("\nThis is printString Function's output")
print(self.inp)
# Test Function
def main():
obj = myClass("salman")
obj.getString()
obj.printString()
if _... |
# Test Function
def main():
words = input("please give the list\n")
words=words.split(',')
# words=words.sort()
words=sorted(list(words))
print(', '.join(words))
if __name__ == "__main__":
main() |
#!/usr/bin/python3
import math
import polynom
def diff1_calculate(values, h):
res = []
y = [y for x,y in values]
for i in range(2):
r = (-3*y[i] + 4*y[i+1] - y[i+2]) / (2*h)
res.append(r)
for i in range(2, len(values)):
#print("3 * {:.4f} - 4 * {:.4f} + {:.4f}".format(y[i], ... |
# output the length of the longest substring without repeating characters
class Solution:
def lengthOfLongestSubstring(self, s: str):
|
def read_input_file():
with open("./input.txt") as file:
for row in file:
yield row.rstrip("\n")
def sum_group_everyone_yes():
total = 0
first_in_group = True
yes_per_group = set()
for line in read_input_file():
# group delimiter
if line == "":
total += len(yes_per_group)
firs... |
import heapq
def read_input_file():
with open("./input.txt") as file:
for row in file:
yield int(row.rstrip("\n"))
def construct_heap():
h = []
for num in read_input_file():
heapq.heappush(h, num)
return h
def joltage_diff():
diffs = {1: 0, 3: 0}
h = construct_heap()
start = 0
while ... |
def read_input_file():
with open("./input.txt") as file:
for row in file:
yield row.strip()
def count_trees():
num_trees = 0
x_coord = 0
for line in read_input_file():
x_coord = x_coord % len(line)
if line[x_coord] == "#":
num_trees += 1
x_coord += 3
print(num_trees)
ret... |
#Type List
def typeList(list):
intsum = 0;
strconcat = "String: ";
for value in list:
if type(value) == int:
intsum += value
if type(value) == float:
intsum += value
if type(value) == str:
strconcat += value + " "
if intsum > 0 and len(strconc... |
# Find Characters
def findCharacters(list, letter):
newList = []
for value in list:
if value.find(letter) >= 0:
newList.append(value)
print newList
findCharacters(['hello','world','my','name','is','Anna'], 'o')
|
"""class Node:
def __init__(self,data):
self.data=data
self.next=None
class sing:
def __init__(self):
self.head=None
def be(self,newda):
newnode=Node(newda)
newnode.next=self.head
self.head=newnode
def dd(self):
val=self.h... |
# 3 1 5 7
# class Solution(object):
# def maxArea(self, array):
def maxArea(array):
water = 0
i, j = 0, len(array) - 1
while i < j:
print i, j
high = min(array[i], array[j])
water = max(water, (j - i) * high)
while array[i] <= high and i < j:
i += 1
... |
#author zyzMarshall
from datetime import datetime
def birth_before_parents_death(indi,childname,childID,childbirthday,parentsdeathdate,death_bool):
"""The birth of a child should within 9 month after the death of their father(if the death
date exist.),and can't born after their mother's death"""
if ... |
from datetime import datetime
def age_cal(birthday): # calculate individual's age
birthdate = datetime.strptime(birthday, '%d%b%Y')
current = datetime.today()
return current.year - birthdate.year - ((current.month, current.day) < (birthdate.month, birthdate.day)) |
with open('./input.txt') as fp:
result = 0
for line in fp:
mass = int(line)
fuel = mass // 3 - 2
result += fuel
print(result)
|
import random
from tkinter import *
while 1:
tk = Tk()
tk.resizable(0,0)
tk.title('呵呵')
canvas = Canvas(tk, width=500, height=500, bg='black', highlightthickness=0)
canvas.pack()
canvas.create_text(250, 250, text='呵呵', font=('Arial', random.randint(50, 300)),fill='green')
tk.update()
|
"""
Sungmin Kim
ball_puzzle.py
"""
from ball_puzzle_animate import *
from stack import *
def first_balls(ball_colors):
"""
takes a string of R G B characters and adds them to the red can stack
"""
red_can = make_empty_stack()
for color in ball_colors:
push(red_can, color)
... |
'''
This program's goal is to allow the user to guess a number between 0 and 1023
inclusive. The program picks the number and if the user picks the correct number,
they will get a message. This code was made by Julian.
'''
'''
This block shows the maximum number of the candy that the machine can hold
and tells the com... |
# Momento 1
programa = sistemas and finanzas
alumno_count = 0
count_sexM = 0
count_sexF = 0
total = 0.0
while true:
alumno = int(input("ingrese nombre de Alumno: "))
average = float(input("Ingrese notas: "))
alumno = alumno_count+1
nota = notas + nota
for i in range (alumno):
print "Es... |
import logging
def f(a, *args):
print(locals())
def f0():
""" a function no args """
print('f0')
d = dict(locals())
for x in d:
print('\t', x, d[x])
def f1(a, b=1):
""" another function, lots of args """
print('f1')
d = dict(locals())
for x in d:
print('\t', x, ... |
#Programa que calcula tu masa corporal
weight = input("Inserta tu peso en kg: ")
height = input("Inserta tu estatura en metros: ")
bmi = round(float(weight)/float(height)**2,2)
print ("Tu indice de masa corporal es: "+str(bmi)) |
#impuestos sobre la renta
income = float(input("Cual es tu renta anual: "))
if income < 10000:
tax = 5
elif income < 20000:
tax = 15
elif income < 35000:
tax = 20
elif income < 60000:
tax = 30
else:
tax=45
print("Tus impuestos son: "+str(tax)+"%") |
def solution (number):
acum=0
for i in range (number):
if i%3==0 or i%5==0:
acum=acum+i
return acum
if __name__=="__main__":
res=solution(500)
print (res) |
import Special_Random
class WaterGun(object):
def __init__(self, capacity, distance=30, stock=False):
# These are things that a WaterGun has.
# All of these should be relevant to our program.
self.capacity = capacity
self.range = distance
self.trigger = True # Someone's tr... |
# ### Problem 3
# Given 2 lists of claim numbers, write the code to merge the 2 lists provided to produce a new list by alternating values between the 2 lists. Once the merge has been completed, print the new list of claim numbers (DO NOT just print the array variable!)
# ```
# # Start with these lists
list_of_claim_nu... |
#!/bin/python3
"""
Given an array (its values as a space separated list), perform d left
rotations taking into account that the array is circular.
"""
import copy
def rot_left(a, d):
# Maybe better like return a[d:] + a[:d]
orig = copy.copy(a) # shallow copy
for i in range(len(a)):
a[i-d] = orig[... |
#!/bin/python3
"""
Given two sentences, the first representing the available words on a magazine
and the second the words needed to write a ransom note. Check if said note can
be writte. Take into account that words are case sensitive.
"""
from collections import Counter
def check_magazine(magazine, note):
can_w... |
#!/bin/python3
"""
Given an array of integer, count the number of triplets (x, y, z) which follow
a geometric progression of a given ratio (r); e.g. for r=5, (5, 25, 125) would
be a triplet.
Triplets do not have to be consecutive, e.g. the can be in positions (0, 4, 10).
"""
from collections import defaultdict, Count... |
#!/bin/python3
"""
Given an array of integers representing the places where a leaf falls,
calculate the time when there are leaves in positions 1 to X (included).
Return -1 if not possible.
"""
# Checking if the sum of the elements is equal to what it should
# (i.e. n*(n+1)//2) would not work because numbers can be c... |
#!/bin/python3
"""
Two strings are anagrams when they contain the same characters with the same
frequency. Calculate the minimum number of characters to remove from them
so they are anagrams.
"""
from collections import Counter
def make_anagram(a, b):
chars_a = Counter(a)
chars_b = Counter(b)
to_remove =... |
#!/bin/python3
"""
Given a list of operations defined as (start index, end index, value) sum up
the value to all index positions between the start and end index. Note that
those indexes start in 1. Return the maximum value of the resulting array.
"""
import itertools
# Trivial but requires more resources than alloc... |
class Spot:
'''
Coordinate object
Contains overloaded functions for comparison, hashing, and addition
'''
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
if self.x == other.x and self.y == other.y:
return True
... |
from stop_watch import start_watch, stop_watch_print
def knapsack(n, m, weights):
if n == 0:
return 0
if m == -1:
return 0
if weights[m] <= n:
return max(weights[m] + knapsack(n - weights[m], m - 1, weights),
knapsack(n, m - 1, weights))
else:
return ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.