text stringlengths 37 1.41M |
|---|
"""
Controller
**********
Description
===========
Controller is used to read and process the game pad input, as well as drive the ROV autonomously.
Functionality
=============
Controller
----------
The :class:`Controller` class provides complex input reading and processing, connected with the :class:`DataManager`.... |
"""Дано целое число, не меньшее 2.
Выведите его наименьший натуральный делитель, отличный от 1.
Формат ввода
Вводится целое положительное число.
Формат вывода
Выведите ответ на задачу."""
n = int(input())
i = 2
while (n % i) != 0:
i += 1
print(str(i))
|
x = int(input())
y = int(input())
if ((y % (y - x + 1)) == 0) and (((x - 1) % (y - x + 1)) == 0):
print('YES')
else:
print('NO')
|
x1 = int(input())
y1 = int(input())
x2 = int(input())
y2 = int(input())
if (x1 == x2) and ((y1 - y2 == 1) or (y1 - y2 == -1)):
print('YES')
elif (y1 == y2) and ((x1 - x2 == 1) or (x1 - x2 == -1)):
print('YES')
elif (x1 == x2 - 1) and ((y1 - y2 == 1) or (y1 - y2 == -1)):
print('YES')
elif (x1 == x2 + 1) and... |
"""Дана последовательность натуральных чисел, завершающаяся числом 0.
Определите, какое наибольшее число подряд идущих элементов
этой последовательности равны друг другу.
Формат ввода
Вводится последовательность целых чисел,
оканчивающаяся числом 0
(само число 0 в последовательность не входит,
а служит как призна... |
ch="a"
def vowel_find(ch):
ch=ch.lower()
if(ch=="a" or ch=="e" or ch=="i" or ch=="o" or ch=="u"):
return "True"
else:
return "False"
print(vowel_find(ch)) |
def find_longest_word(a):
longest=0
for i,val in enumerate(a):
if(len(val)>longest):
longest=len(val)
return longest
a=["finding","the","length","of","longest","word","in","this","sentence"]
print(find_longest_word(a)) |
##########################
##Exercicio 1: Contar o número de palavras no arquivo.
###################################
import fileinput
contador = 0
for s in fileinput.input("aux/Palavras.txt"):
contador = contador + 1
print "Existem", contador, "palavras no arquivo Palavras.txt\n"
##########################
##E... |
amount=int(input("enter the salary "))
totalsal=amount*12
tax=0
if totalsal<250000:
print("no Tax")
elif totalsal<500000:
tax=0.05*totalsal
print("tax to be paid:Rs.",tax)
elif totalsal<1000000:
tax=0.2*totalsal
print("tax to be paid:Rs.",tax)
else:
tax=0.3*totalsal
print("tax t... |
"""
1. Сгенерировать список случайной длины заполнив его случайными числами
(используйте random, диапазон чисел произвольный)
2. Вывести на экран числа из списка в обратном порядке через пробел
3. Извлечь первое число, возвести его в квадрат и вставить в средину списка
4. Удалить из списка простые ч... |
"""
Программу принимает на ввод строку string и число n.
Выводит на экран строку с смещенными символами на число n.
Весь код можно написать в одной функции main,
но рекомендуется разбить код на несколько функций, например:
- main
- функция для получения не пустой строки.
- функция для получе... |
print "x",
for a in range(1,13):
print a,
print ""
for i in range(0,13):
if i > 0:
print i, i*1, i*2, i*3, i*4, i*5, i*6, i*7, i*8, i*9, i*10, i*11, i*12
|
class Bike(object):
# init function to set attributes of Bike object
# include Bike name to differentiate various instances
# all Bikes will start at 0 miles
def __init__(self, name, price, max_speed):
self.name = name
self.price = price
self.max_speed = max_speed
self.mi... |
"""
The current code given is for the Assignment 1.
You will be expected to use this to make trees for:
> discrete input, discrete output
> real input, real output
> real input, discrete output
> discrete input, real output
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from .utils import e... |
from bs4 import BeautifulSoup as bs
from splinter import Browser
import pandas as pd
from time import sleep
import requests
def init_browser():
# @NOTE: Replace the path with your actual path to the chromedriver
executable_path = {"executable_path": "chromedriver"}
return Browser("chrome", **executable_pa... |
dia = int(input('Por quantos dias você ficou com o carro: '))
km = float (input('Qual a kilometragem percorrida com o carro ? '))
aluguel = dia 60
kilometragem = km 0.15
print('O total a pagar é de R$ {:.2f} ' .format(aluguel+kilometragem))
|
#
# @lc app=leetcode.cn id=818 lang=python3
#
# [818] 赛车
#
# @lc code=start
class Solution:
# https://leetcode.com/problems/race-car/discuss/124326/Summary-of-the-BFS-and-DP-solutions-with-intuitive-explanation
# 这个把题目读明白已经是很有挑战的事
# 注意位运算符运算优先级低于加减号
# 状态定义 dp(i) 为走到位置i,需要的最少指令数
# 分为三种情况
# 1.先走... |
#解法1 并查集 加了parent 数组和rank秩,路径压缩
class UnionFind:
def __init__(self,n):
self.count = n
self.parent = [i for i in range(n)]
self.rank = [1 for i in range(n)]
def get_count(self):
return self.count
def find(self,p):
while p != self.parent[p]:
self.... |
def remove_duplicates(nums):
"""
:type nums: List[int]
:rtype: int
"""
i = 0
for j in range(1, len(nums)):
if nums[i] != nums[j]:
nums[i+1] = nums[j]
i += 1
return i+1
if __name__ == '__main__':
print(remove_duplicates([1, 1, 2]))
|
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
# sort O(nlogn)
# if len(s) != len(t):
# return False
# if sorted(s) != sorted(t):
# return False
# return True
#... |
# -*- coding: utf-8 -*-
"""https://leetcode-cn.com/problems/counting-bits/"""
from typing import List
class Solution:
def countBits(self, num: int) -> List[int]:
res = [0]
for i in range(1, num + 1):
if i%2 == 0:
# i 为偶数, 二进制中1的个数为其1/2数二进制中的1个数
# 位运算<<,表示... |
#假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。对每个孩子 i ,都有一个胃口值 gi ,这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j ,都有一个尺寸 sj 。如果 sj >= gi ,我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。
#
# 注意:
#
# 你可以假设胃口值为正。
#一个小朋友最多只能拥有一块饼干。
#
# 示例 1:
#
#
#输入: [1,2,3], [1,1]
#
#输出: 1
#
#解释:
#你有三个孩子和两块小饼干,3个孩子的胃口值分别是:1,2,3。
#虽然你有两块小饼... |
import collections
from typing import List
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
hashMap = collections.defaultdict(list)
for str in strs:
count = [0] * 26
for char in str:
count[ord(char) - ord('a')] += 1
h... |
class Solution:
def reverseWords(self, s: str) -> str:
if not s:
return ''
strList = s.split(' ')
result = ''
for word in strList:
temp = ''
for i in range(len(word)):
temp += word[len(word) - i - 1]
result += ' ' + temp... |
#假设按照升序排序的数组在预先未知的某个点上进行了旋转。
#
# ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
#
# 搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。
#
# 你可以假设数组中不存在重复的元素。
#
# 你的算法时间复杂度必须是 O(log n) 级别。
#
# 示例 1:
#
# 输入: nums = [4,5,6,7,0,1,2], target = 0
#输出: 4
#
#
# 示例 2:
#
# 输入: nums = [4,5,6,7,0,1,2], target = 3
#输出: -1
# Related ... |
#解法1数学法
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
#数学:平铺面积算法: 以最高高度的墙高 为高度,高 h = max(height),宽 w = len(height),面积 s = h * w
#从左到右遍历 找左边最高的墙,从右到做遍历,找右边最高的墙,算面积1, 面积1多算了最高高度的面积,所以减掉最高高度的面积, s1 = s1 - h * w
#剩下的面... |
#
# @lc app=leetcode.cn id=94 lang=python3
#
# [94] 二叉树的中序遍历
#
# https://leetcode-cn.com/problems/binary-tree-inorder-traversal/description/
#
# algorithms
# Medium (69.12%)
# Likes: 340
# Dislikes: 0
# Total Accepted: 84.3K
# Total Submissions: 121.8K
# Testcase Example: '[1,null,2,3]'
#
# 给定一个二叉树,返回它的中序 遍历。
# ... |
# 322. Coin Change
class Solution(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
memo = {0: 0}
def helper(n):
if n in memo:
return memo[n]
... |
#解法1:字典树 + dfs
def findWords(board, words):
"""
:type board: List[List[str]]
:type words: List[str]
:rtype: List[str]
"""
#dfs
def dfs(i,j,t,s):
ch = board[i][j]
if ch not in t:
return #递归终止条件
t = t... |
# -*- coding: utf-8 -*-
# @Time : 2019-12-13 09:49
# @Author : songzhenxi
# @Email : songzx_2326@163.com
# @File : LeetCode_84_1034.py
# @Software: PyCharm
# 给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
# 求在该柱状图中,能够勾勒出来的矩形的最大面积。
# 以上是柱状图的示例,其中每个柱子的宽度为 1,给定的高度为 [2,1,5,6,2,3]。
# 图中阴影部分为所能勾勒出的最大矩形面积,其面积为 10 个单位。... |
#给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
#
# 例如:
#给定二叉树: [3,9,20,null,null,15,7],
#
# 3
# / \
# 9 20
# / \
# 15 7
#
#
# 返回其层次遍历结果:
#
# [
# [3],
# [9,20],
# [15,7]
#]
#
# Related Topics 树 广度优先搜索
from typing import List
class TreeNode(object):
def __init__(self, x):
self.val = x
... |
#给定两个字符串 text1 和 text2,返回这两个字符串的最长公共子序列。
#
# 一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。
#例如,"ace" 是 "abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列。两个字符串的「公共子序列」是这两个字符串所共同拥有的子序列。
#
# 若这两个字符串没有公共子序列,则返回 0。
#
#
#
# 示例 1:
#
# 输入:text1 = "abcde", text2 = "ace"
#输出:3
#解释:最长公共子序列是 "ace",它的长度为 3。
#
#
# 示例 2... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#递归
# class Solution:
# def preorderTraversal(self, root: TreeNode) -> List[int]:
# result = []
# def helper(root, result):
# ... |
class Solution:
def reverseWords(self, s: str) -> str:
import re
str1 = re.findall(r'\S+', s)
if len(str1) == 0:
return ''
str1 = str1[::-1]
str2 = ''
for i in range(len(str1) -1):
str2 += (str1[i] + ' ')
return str2 + str1[-1]
|
#
# @lc app=leetcode.cn id=541 lang=python3
#
# [541] 反转字符串 II
#
# https://leetcode-cn.com/problems/reverse-string-ii/description/
#
# algorithms
# Easy (50.28%)
# Likes: 58
# Dislikes: 0
# Total Accepted: 10.3K
# Total Submissions: 20.1K
# Testcase Example: '"abcdefg"\n2'
#
# 给定一个字符串和一个整数 k,你需要对从字符串开头算起的每个 2k 个... |
# -*- coding: utf-8 -*-
"""https://leetcode-cn.com/problems/merge-two-sorted-lists"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 将输入列表转换为链表
def initList(self, data):
if len(data) == 0:
re... |
#给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
#
# 示例:
#
# 输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
#输出:
#[
# ["ate","eat","tea"],
# ["nat","tan"],
# ["bat"]
#]
#
# 说明:
#
#
# 所有输入均为小写字母。
# 不考虑答案输出的顺序。
#
# Related Topics 哈希表 字符串
from typing import List
#leetcode submit region begin(Prohibit modificatio... |
#给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
#
# 例如,给出 n = 3,生成结果为:
#
# [
# "((()))",
# "(()())",
# "(())()",
# "()(())",
# "()()()"
#]
#
# Related Topics 字符串 回溯算法
#leetcode submit region begin(Prohibit modification and deletion)
class Solution(object):
def generateParenthesis(self, n):
"""
... |
"""
排序相关
https://mp.weixin.qq.com/s/Qf416rfT4pwURpW3aDHuCg
"""
class SortAlgorithm:
@classmethod
def bubble_sort(cls, arr):
"""冒泡排序"""
i = 0
while i < len(arr) - 1:
j = 0
is_sorted = True
while j < len(arr) - 1 - i:
# print(arr, 'i:'... |
#
# @lc app=leetcode.cn id=105 lang=python3
#
# [105] 从前序与中序遍历序列构造二叉树
#
# https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/
#
# algorithms
# Medium (62.93%)
# Likes: 289
# Dislikes: 0
# Total Accepted: 34.2K
# Total Submissions: 54.3K
# Testcase Example: '[3,... |
"""
590. N-ary Tree Postorder Traversal
Given an n-ary tree, return the postorder traversal of its nodes' values.
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
Follow up:
Recursive solution is trivial, could you ... |
#
# @lc app=leetcode.cn id=429 lang=python3
#
# [429] N叉树的层序遍历
#
# @lc code=start
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
# class Solution:
# # 每层记录节点的值,放到数组中,并记录下一层的children。重复之前的操作
# def levelOrder(s... |
import sys
import itertools
class SumPairMatcher(object):
"""
#Program that accepts a list of integers separated by spaces and a target integer.
#Prints out all of the pairs of numbers from the input list that sum to the target integer.
#Sorts lists so smaller values are shown first.
"""
def getLine(self):
... |
#!/usr/bin/env python
def numFactors(n):
factors = 2
for i in xrange( 2, (n/2)+1 ):
if( n % i == 0 ):
factors += 1
return factors
i = 1
biggest_n = 0
triangle = i
while( True ):
i += 1
triangle += i
n = numFactors(triangle)
if( n > biggest_n ):
biggest_n = n
print tri... |
#####
### Matthew Nuckolls
### Project Euler #32
### Production Code
#####
def digits(*args):
result = set()
for arg in args:
result = result.union(set([int(i) for i in str(arg)]))
return result
def pandigital(*args):
length = sum([len(str(arg)) for arg in args])
if length !=... |
#!/usr/bin/env python
#
# Project Euler 94
# a^2 + b^2 = c^2
# c^2 - b^2 = a^2
from math import sqrt
def is_square(n):
m = int(sqrt(n))
return n == m * m
def is_valid(c,a):
return is_square(c*c - a*a)
def high(c):
return is_valid(c, c/2 + 1)
def low(c):
return is_valid(c, c/2)
def both(c):
... |
#!/usr/bin/env python
#
# Project Euler 58
from bitarray import bitarray
from math import sqrt
def generate_primes():
size = 10 ** 9
stop = int(sqrt(size))
a = bitarray(size)
a.setall(True)
a[:2] = False
primes = list()
next = 2
try:
while True:
primes.append(next... |
#!/usr/bin/env python
sum = 0
for i in xrange(1000):
if( (i % 3 == 0) or (i % 5 == 0) ):
sum += i
print sum
print sum(x for x in xrange(1000) if (x % 3 == 0 or x % 5 == 0))
|
#!/usr/bin/python
import os
import subprocess
import sys
# Return codes
# 1 : No command is given
# -1 : Error in command excecution or in command syntax
def run_command(command=None):
"""
This module runs the command input to it.
On Success returns output
On failure returns -1
On no input st... |
#This program tracks grades from students and collects an average.
runtotal = float(0)
count = int(0)
avg = float(0)
sent = int(0)
#ask the user for the grade
num = int(input('Please enter the first grade. Enter -1 to stop. '))
sent = 1
while sent == 1:
if num >= 0:
if num > 100:
num = int(... |
#Mary Jacobsen
#Project 2 - file transer system
#client side
import sys
from socket import *
#This function sets up the data socket
#It is mostly from Project 1
def getSocket():
if sys.argv[3] == "-l": #if command is -l, <SERVER_HOST>, <SERVER_PORT>, <COMMAND>, <DATA_PORT>
numArguments = 4
elif sys.ar... |
import math
import Dif_Helman
class Input:
@staticmethod
def count_digits(n):
if n == 0:
return 0
return 1 + n.count_digits(n // 10)
@staticmethod
def binary_input():
binary = int(input("Введите число в двоичном виде (до 10 символов): "),2)
try:
... |
# Важная информация! По ссылке объяснение как .py файлы компилировать в .exe
# http://nikovit.ru/blog/samyy-prostoy-sposob-skompilirovat-python-fayl-v-exe/
import ProbabilityTest
import DivisionTest
# main
def main():
print('\n')
print("Начало выполнения программы")
while True:
test_method = int(... |
import random
n = int(input ("Masukkan jumlah n ="))
for i in range (n):
while 1:
n = random.random()
if n < 0.5 :
break
print(n) |
t = int(input())
for i in range(t):
num = int(input())
num = str(num)
if num[::-1] == num:
print("wins")
else:
print("losses")
|
import basicfunctions as bf
#loss function
def loss(fwdprop,correct):
return (correct-fwdprop)**2
def lossList(fwdpropList,correctList):
lost = 0
min = bf.minLenTwo(fwdpropList,correctList)
for i in range(0,min):
lost += loss(fwdpropList[i],correctList[i])
return lost/min
#print(lossList([1,5,5,4,6,8,4,21,3... |
# Write a program which can compute the factorial of a given numbers.
# The results should be printed in a comma-separated sequence on a single line.
def fact(x):
if x == 0:
return 1
return (x * fact(x -1))
x = int(input())
print(fact(x)) |
for i in range(1,6):
print(" "*(5-i)+"$"*i)
print("\n\n")
for i in range(0,5):
print(" "*i+"$"*(5-i))
for i in range(1,6):
print(" "*(5-i)+"$"*(2*i-1))
for i in range(0,5):
print(" "*i+"$"*(9-2*i)) |
import pickle
import random
from helper import *
def generate_random_initial_sequence(INPUT_SEQUENCE_LENGTH):
WEIGHTS_COUNTER = int(input("Enter weight file number to generate the seed: "))
print("[!]INFO: Generating random seed notes.")
try:
note_to_int = get_note_to_int(WEIGHTS_COUNTER)
... |
'''
Created on 26 avr. 2013
@author: Alexis Thongvan
The purpose of this code is to move a sheet across the
existing one
'''
from Basics import openExcel, openWorkbook, saveCopy, closeExcel
xl = openExcel()
wb = openWorkbook("../files/testWorkbook.xlsx", xl)
def MoveSheet(sheet, new_position, wb):
"""sheet can ... |
'''
Created on 8 mai 2013
@author: thongvan
Rename a sheet
'''
from Basics import openExcel, openWorkbook, saveCopy, closeExcel
xl = openExcel()
wb = openWorkbook("../files/testWorkbook.xlsx", xl)
def renameSheet(old_sheet, new_name, wb):
"""Rename a sheet to a new name, old
sheet can be the number of the s... |
# price conditions
MIN_PRICE = 800
MAX_PRICE = 1500
# area conditions
MIN_AREA = 8.0
MAX_AREA = 20.0
# direction condition
DIRECTION = ['南', '北', '东', '西']
# location condition
def handle(data):
if not data:
return False
# filter status
room_status = data['room_status']
print('room_stat... |
"""A Python implementation of LaserLang"""
import argparse
import operator
import sys
import math
NORTH = [0, 1]
SOUTH = [0, -1]
EAST = [1, 0]
WEST = [-1, 0]
INSTRUCTION = 0
STRING = 1
RAW = 2
CONDITIONALS = "⌞⌜⌟⌝"
MIRRORS = "\\/>v<^" + CONDITIONALS
NULLARY = "crRpPoOnB "
UNARY = "()!~b"
BINARY = "+-×÷*gl=&|%"
def... |
#github username: ahal1779
#github email:ahal1779@colorado.edu
#Ahmed M Alismail
import Queue
class myQueue():
def __init__(this):
this.q = Queue.Queue()#create new Q
def putq(this,value):
this.q.put(value)#add using the put function
def popq(this):
while not this.q.empty():# if the queue is not empty print t... |
import string
import random
for i in range(0, 3):
file = open("file" + str(i) + ".txt", "w")
fileText = ""
for j in range(0, 10):
fileText += random.choice(string.ascii_lowercase)
file.write(fileText + "\n")
print(fileText)
numa = random.randint(1, 42)
numb = random.randint(1, ... |
# Um professor quer sortear um dos seus quatro alunos para apagar o quadro.
# Faça um programa que ajude ele, lendo o nome dos alunos e escrevendo na tela
# o nome do escolhido#
import random
nome0 = input('Digite um nome: ')
nome1 = input('Digite um nome: ')
nome2 = input('Digite um nome: ')
nome3 = input('Digite um n... |
#Crie um programa que leia um número Real qualquer pelo teclado e mostre na tela a sua porção inteira.
import math
num = float(input('Digite um número: '))
print("A parte real do número {} é {}".format(num,math.trunc(num))) |
# Escreva um programa que leia a velocidade de um carro.
# Se ele ultrapassar 80Km/h, mostre uma mensagem dizendo
# que ele foi multado. A multa vai custar R$7,00 por
# cada Km acima do limite.
velocidade = int(input('Digite a velocidade do veículo: '))
if velocidade > 80:
multa = (velocidade-80) * 7
print('V... |
# Crie um programa que leia o nome completo de uma pessoa e mostre:
# O nome com todas as letras maiúsculas e minúsculas.
# Quantas letras ao todo (sem considerar espaços).
# Quantas letras tem o primeiro nome.
nome = input('Nome completo: ').strip()
print(nome.upper())
print(nome.lower())
print(len(nome) - nome.co... |
# Слово по буквам
# Демонстрирует применение цикла for к строке
word = input("Введите слово: ")
print("\nBoт все буквы вашего слова по порядку:")
for letter in word :
print (letter)
input("\n\nHaжмитe Enter. чтобы выйти . ") |
name = input("what i your name?\n")
age = int(input("your old\n"))
weight = int(input("your weight\n"))
print("\nyour parametrs", name, weight, age) |
# Метрдотель
# Демонстрирует условную интерпретацию значений
print("Добро пожаловать в Шато-де-Перекуси!")
print("Кажется, нынешним вечером у нас все столики заняти. \n")
money = int(input ("Сколько долларов вы готовы дать метрдотелю на чай?\n"))
if money:
print("Прошу прощения, мне сейчас сообщили, что есть один с... |
#!/usr/bin/env python3
# file: quick_sort.py
# auth: Jack Lee
# Date: Jan 31, 2017
# Desc: implementation of quick sort algorithm
# https://en.wikipedia.org/wiki/Quicksort
#
import random
#
# func: partition(array, low, high)
# desc: find the pivot for the array to quick sort
# on the left of pivot, less... |
# YouTube Video: https://youtu.be/6qo3ly3-_I8
# Gets the first name from the the full name string
fullname = "John Jacob"
# Start from position 0(first position of string)
# Stop before position 4
firstname = fullname[0:4]
# Print the first name
print (firstname)
|
# example = 'test'
# 'a' -> 'b'
# # ord()
# String -> 'test'
# ASCII -> ord('a') = 97
# for Loop
# chr(97) = a
#userInput = input("String to encrypt: ")
userInput = 'abc'
encryptedOutput = ''
incBy = input("Increment by? ")
incBy = '1'
# isDig = '22'.isdigit()
# print(isDig)
key = int(incBy)
print("actualInput... |
# # # x = [3,2,1]
# # # # x.__sizeof__()
# # # # if 2 in x:
# # # # print(x.index(2)) if 2 in x
# # # x.append(4)
# # # x.extend([1,2,3])
# # # x.insert(0, 9)
# # # x.remove(3)
# # # x.pop(1)
# # # print(x.count(1))
# # # # x=[]
# # # # x.extend(['a','x'])
# # # # print(x.index(9,0, 9))
# # # # x.clear()
# # # x.r... |
from collections import namedtuple
individual = namedtuple("ndividual", "name age height")
user = individual(name="Homer", age=37, height=178)
print(user)
# print(user[name])
|
import sqlite3
import uuid
#アカウント管理
class AccountDao:
dbname = 'account.db'
def __init__(self):
conn = sqlite3.connect(self.dbname)
cur = conn.cursor()
# アカウント管理テーブル
cur.execute("CREATE TABLE IF NOT EXISTS account(id, name, password);")
conn.commit()
conn.close()... |
hours = int(input())
minutes = int(input())
if hours > 12:
hours %= 12
if minutes > 60:
minutes %= 60
if hours == 12:
hours = 0
if minutes == 60:
minutes = 0
degreesPerCircle = 360
degreesPerHour = degreesPerCircle / 12
degreesPerMinute = degreesPerCircle / 60
allDegreesInHours = hour... |
str1 = "Yush"
str2 = "contributes in"
str3 = "Hacktoberfest2021"
# Type-1
concat = str1 +" " +str2 +" "+str3
print(type(concat))
print(concat)
# Type-2
concat1 = " ".join((str1,str2,str3))
print(type(concat1))
print(concat1)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of Advent of Code 2020
# https://github.com/scorphus/advent-of-code-2020
# Licensed under the BSD-3-Clause license:
# https://opensource.org/licenses/BSD-3-Clause
# Copyright (c) 2020, Pablo S. Blum de Aguiar <scorphus@gmail.com>
from aoc import integ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of Advent of Code 2020
# https://github.com/scorphus/advent-of-code-2020
# Licensed under the BSD-3-Clause license:
# https://opensource.org/licenses/BSD-3-Clause
# Copyright (c) 2020, Pablo S. Blum de Aguiar <scorphus@gmail.com>
import collections
im... |
# #1 задача
def print_my_name(my_name):
print(my_name)
print_my_name("kirill")
#2 задача 3 задача
def calculator(num1, num2, action):
if action == "+":
result = num1 + num2
print(result)
elif action == "-":
result = num1 - num2
print(result)
elif action == "/":
... |
# 1 задача
presents = {"скейтборд", "футболку", "рюкзак", "цукерки (5 кг)", "мандарини"}
for i in presents:
if i == "скейтборд":
print("так скейтборд є")
# 2 задача
money = {100, 200, 150, 300}
sum_ = sum(money)
mod_money = 200
all_money = sum_ + mod_money
print (all_money)
# 3 задача
gomer = {"Піцу", "... |
# 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 postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
... |
#%%
from abc import ABCMeta, abstractmethod
# %%
class Context(metaclass=ABCMeta):
"""the context of envirnment class in state pattern"""
def __init__(self):
self._states = []
self._curState = None
# the attribute that state depends on as changing
# set this variable as a singl... |
# -*- coding: utf-8 -*-
"""
CS231n http://cs231n.github.io/
"""
import numpy as np
from itertools import product
"""The implementation of KNN given below uses the following numpy functions:
* np.bincount
* np.argmax
* np.argpartition https://stackoverflow.com/questions/34226400/find-the-k-smallest-values-of-a-numpy-a... |
# -*- coding: utf-8 -*-
import numpy as np
from .layers import *
class FullyConnectedNet:
"""
A fully-connected neural network with an arbitrary number of hidden layers, ReLU nonlinearities,
and a softmax loss function. This will also implement dropout and batch normalization as options.
For a netwo... |
def my_prime(n):
for i in range(2,n):
if n%i==0:
return False
else:
return True
number1=int(input('Enter number1: '))
number2=int(input('Enter number2: '))
for i in range(number1,number2+1):
if my_prime(i)==True:
print(i,end=',')
|
array=[]
size = int(input('Enter array size : '))
for i in range(size):
inp = int(input("Enter arr[%d] : " %(i)))
array.append(inp)
searchnum = int(input("Enter num to be searched : "))
flag=0
for i in range(len(array)):
if(array[i] == searchnum):
index=i
flag=1
if(flag == 0):
print("not found")
else:
prin... |
from operator import itemgetter
class Book:
"""Книга"""
def __init__(self, id, title, autor, price, store_id):
self.id = id
self.title = title
self.autor = autor
self.price = price
self.store_id = store_id
class Store:
"""Книжный магазин"""
def __init__(self... |
#!/usr/bin/env python
def quicksort(lista, inicio, fim):
if(inicio < fim):
pivor = particionamento(lista, inicio, fim)
# print("{}".format(pivor))
quicksort(lista, inicio, pivor)
quicksort(lista, pivor+1, fim)
def particionamento(lista, inicio, fim):
x, y, pivor, temp = inicio... |
from vector import Vector
from operation import cross
def vertical(v1,v2):
# get the vector is vertical to the plane determined by v1 and v2
# if v1 and v2 can not determine a plane, return unit vector
c = cross(v1,v2).normalize()
if c.length() > 0:
return c
return Vector(1,0,0)
|
""""
This analysis is mostly interesting when we start to handle inheritance. It is a more trivial case than __dict__ in
datalog we can recognize when there is an assignment to the bases field and the baseHeap is a class. However
we need a way to deal with tuples in our analysis.
"""
class Pair(object):
def __init... |
# Use a stack to check whether a string has balanced usage of parentheses and brackets
# Balanced: {([()])}
# Not Balanced: {([())}]
# Could alternatively import the stack created in stack_example.py
# from stack_example import Stack
class Stack():
def __init__(self):
self.items = []
def push(self, ... |
from urllib.request import urlopen
from bs4 import BeautifulSoup
import tkinter as tk
from datetime import date
def get_price():
'''
Gets The Current Bitcoin Price From The Website
'''
url = "https://www.coindesk.com/price/bitcoin"
page = urlopen(url)
html_bytes = page.read()
html = html_... |
class A:
pass
a = A()
print(a.__class__) # <class '__main__.A'> 实例化对象是由类创建出来的
print(A.__class__) # <class 'type'>类是由type即元类创建出来的
num = 10
print(num.__class__) # <class 'int'> 10是由int 类创建出来的
print(int.__class__) # <class 'type'>int类也是由元类创建出来 的
l = "oooo"
print(l.__class__) # <class 'str'>
print(str.__class... |
def f(x):
while x > 3:
f(x + 1)
print x
def Square(x):
return SquareHelper(abs(x), abs(x))
def SquareHelper(n, x):
if n == 0:
return 0
return SquareHelper(n-1, x) + x
def evalQuadratic(a, b, c, x):
return a * x * x + b * x + c
def twoQuadratics(a1, b1, c1, x1, a2, b2, c2, x2):
return evalQua... |
import wikipedia as wiki
from random import randint
# Option 1: Downloaded https://github.com/daxeel/TinyURL-Python
# change urllib2 to urllib3 in the tinyurl.py file and install using # python3 setup.py install
# Didn't work
#import tinyurl
# Option 2: Download https://github.com/IzunaDevs/TinyURL
# Edit the file set... |
# Part 1
with open('day-1-input.txt') as f:
module_masses = [int(line.strip()) for line in f]
fuel_requirements = [m//3 - 2 for m in module_masses]
total_fuel_required = sum(fuel_requirements)
print(total_fuel_required)
# Part 2
def fuel(m):
"""
Determine the total fuel required for a given module mass,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.