text stringlengths 37 1.41M |
|---|
#Escribir un programa que almacene el abecedario en una lista, elimine de la lista las letras que ocupen posiciones múltiplos de 3,
#y muestre por pantalla la lista resultante
abecedario=["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"]
for i in range(len(a... |
#Escribir una función a la que se le pase una cadena <nombre> y muestre por pantalla el saludo ¡hola <nombre>!.
def Saludo(nombre):
"""
Funcion que devuelve un saludo por pantalla
Parametros:
nombre: Nombre de usuario
"""
print("¡Hola "+nombre+"!")
return
izena=str(input("Introduzca su nomb... |
#Escribir una función que calcule el total de una factura tras aplicarle el IVA.
# La función debe recibir la cantidad sin IVA y el porcentaje de IVA a aplicar, y devolver el total de la factura.
# Si se invoca la función sin pasarle el porcentaje de IVA, deberá aplicar un 21%.
def Factura(cantidad,iva=21):
"""
... |
import os
import sys
class Point:
x = 0
y = 0
signal = 0
def __init__(self, x, y, signal):
self.x = x
self.y = y
self.signal = signal
def __eq__(self, other):
return self.x, self.y == other.x, other.y
def __hash__(self):
return hash((str(self.x), str(s... |
class DictEntry:
""" Dictionary entry
word - word in foreign language ,
translation - in native language
learn index - int in range [0,100]
"""
def __init__(self, spelling: str, translation: str, learning_index: int, sql_id: int = 0) -> None:
self.spelling = ... |
def toLowerCase(sym): #function that changes uppercase to lowercase symbol
return sym+32 if 65 <= sym and sym <= 90 else sym #if symbol is in range [65; 90] we should add 32 to make lowercase symbol
def main(): #main function that will write ASCII of uppercase symbol and return ASCII of uppercase
symbol = ... |
# ======= DEFINE LIBRARIES ======= #
import matplotlib.pyplot as plt #Graph plotting tools
import math #Mathematical functions
import time as time_ #Time measurement functions
import numpy as np #Basic fucntions toolkit
import sys ... |
def three_loops(array):
n = len(array)
max_sum = array[0]
for start in range(n):
for end in range(start, n):
current_sum = sum(array[start:end+1])
# print(array[start:end+1])
if current_sum > max_sum:
max_sum = current_sum
# print(max_sum)
return max_sum
def two_loops(array):
n = len(array)
m... |
#Get the feet from the user:
meters = float(input("Enter the number in feet:"))
meters_in_ft= meters*0.305
print(meters_in_ft, "meters")
|
from random import shuffle
class Blackjack():
def __init__(self, starting_chips):
self.chips = starting_chips
self.short = True
self.humhand = []
self.aihand = []
self.deck = []
self.makeDeck()
# self.runout = []
def makeDeck(self):
self.deck = l... |
from operator import __add__ as _add
from functools import reduce
from pybs.utils import memoized2 as memoized
@memoized
def number_of_trees_of_order(n):
"""Returns the number of unordered rooted trees with exactly *n* vertices.
Uses a formula from Sloane's OEIS sequence no. ``A000081``.
"""
if n < ... |
# PROGRAM NAME: simple_nn.py
# PROGRAM PURPOSE: Creates a very barebones neural network
# PROGRAMMER: Dillon Pietsch
# DATE WRITTEN: 8/15/17
# Initialize weight of singular node for NN
weight = 0.1
def neural_network(input, weight):
prediction = input * weight
return prediction
# 1-D Test Data
number_of_toes... |
#!/usr/bin/env python2.7
#File: lebailly/BME205/HW1/wordcount
#Author: Chris LeBailly
"""
wordcount counts the number of "words" (a contiguous sequence of characters from
the set {abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'}) in stdin.
Results can be sorted alphabetically (--alpha), by count descending ... |
import requests
import json
urlAwesome = "https://economia.awesomeapi.com.br/last/USD-BRL,EUR-BRL,BTC-BRL"
cotacoes = requests.get(urlAwesome)
cotacoes = cotacoes.json()
while True:
print("Converta dinheiro real para qualquer outro")
print()
print("1 - DÓLAR")
print("2 - EURO")
print("3 - BITCOIN... |
grade=float(input("Enter your total points: "))
if grade >= 90:
print("Congratulations you got an A")
elif grade >= 80:
print("Congratulation you got B")
elif grade >= 70:
print("congratulations you got C")
elif grade >= 60:
print("Not much just D")
else:
print("You suck!! go and study harder")
|
class Solution(object):
def pivotIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
length = len(nums)
if length < 3:
return -1
sum_from_right = [0]
i = length-1
while i >= 0:
... |
from abc import ABC, abstractmethod
class BaseValidator(ABC):
# позволяет привязать имя поля, к которому относится дескриптор
def __set_name__(self, owner, name):
self.field_name = name
def __get__(self, instance, owner):
return instance.__dict__[self.field_name]
def __set__(self, in... |
import time as t
import math
def TotExecution_Time(func):
def inner(n):
starttime= t.time()
func(num)
endtime = t.time()
print("The total execution time taken:",endtime-starttime)
return inner
@TotExecution_Time
def Factorial(n):
fact = 1
if num < 0:
print("Sorr... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Unicode and string related functions
"""
import unicodedata
def unicoderemove(s, category_check):
'''
Remove characters of certain categories from the unicode string
Args:
s (str): input string, assumed in utf8 encoding if it is a bytestring
... |
import unittest
from decimal import Decimal
from util import alert
class TestDict(unittest.TestCase):
def test_alert(self):
rate = 1
# 初始上涨3.5%,报警
cache_rate, diff, is_alert = alert(10.35, 10, rate=rate)
print(cache_rate, diff)
self.assertEqual(cache_rate, Decimal('3.5'))
... |
"""
Prashanth Khambhammettu (prashanth31@gmail.com)
2013/02/20 : Summation of Sine Waves
"""
import matplotlib.pyplot as plt
import numpy as np
import math as math
import sys
"""
Sine function
Returns an array of times and values of sin(pi*n*t) /n
where t belongs to [-1,1]
n is the input parameter
"""
def xn(n):
... |
print('Hello')
#создадим список и сразу выводим его
spisok2 = ['Gosha','Max','Denis']
print(spisok2)
#Добавим в список переменную
spisok2.append('Alex')
print(spisok2)
#создадим ещё один список и добавим всё его содержимое в первый
spisok1 = ['Gordon']
spisok2.extend(spisok1)
print(spisok2)
#удаляем из списка конкре... |
# author: tornado2
answer = input ("HELLO")
answer = answer.lower()
word = answer.split()
if word[0] = "how":
if word[1] = "do":
if word[2] = "you":
if word[3] = "do":
print "I'm fine"
if word[1] = "are":
if word[2] = "you":
if word[3] = "a":
if word[4] = "robot":
print "I am not a robot. I am ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 19 14:20:29 2020
@author: USER
"""
def circle_area(x):
num=x*x*3.14
return num
def circle_circum(x):
num=x*2*3.14
return num
circle_area(n)
n= int(input("number"))
print(n)
n= int(input("number"))
cicle_circum(n)
print(n) |
# my first python script
quotes = {
"Moe": "A wise guy, huh?",
"Larry": "Ow!",
"Curly": "Nyuk nyuk!",
}
stooge = "Larry"
print(stooge, "says:", quotes[stooge])
language = 7
print("Language %s: I am Python. What's for supper?")
print(language, "I am Python. What's for supper?")
stooge = "Moe"
print(quotes[stooge])
|
# Opening file
readFile = open("poojith.txt", "r")
# running a loop for every line in the file
for line in readFile:
#You can use the len method to find how many chracters there are.
#lengthofLine = len(str(line))
#print(lengthofLine)
if 'Python' in line:
#using the replace method I was able t... |
# 给定一个可包含重复数字的序列,返回所有不重复的全排列。
#
# 示例:
#
# 输入: [1,1,2]
# 输出:
# [
# [1,1,2],
# [1,2,1],
# [2,1,1]
# ]
# Related Topics 回溯算法
# leetcode submit region begin(Prohibit modification and deletion)
class Solution(object):
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: Lis... |
# 给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
#
# 求在该柱状图中,能够勾勒出来的矩形的最大面积。
#
#
#
#
#
# 以上是柱状图的示例,其中每个柱子的宽度为 1,给定的高度为 [2,1,5,6,2,3]。
#
#
#
#
#
# 图中阴影部分为所能勾勒出的最大矩形面积,其面积为 10 个单位。
#
#
#
# 示例:
#
# 输入: [2,1,5,6,2,3]
# 输出: 10
# Related Topics 栈 数组
# leetcode submit region begin(Prohibit modification and deletion)
cla... |
# 有个内含单词的超大文本文件,给定任意两个单词,找出在这个文件中这两个单词的最短距离(相隔单词数)。如果寻找过程在这个文件中会重复多次,而每次寻找的单词不同,
# 你能对此优化吗?
#
# 示例:
#
# 输入:words = ["I","am","a","student","from","a","university","in","a","city"],
# word1 = "a", word2 = "student"
# 输出:1
#
# 提示:
#
#
# words.length <= 100000
#
# Related Topics 双指针 字符串
# leetcode submit region beg... |
# 你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金。这个地方所有的房屋都围成一圈,这意味着第一个房屋和最后一个房屋是紧挨着的。同时,相邻的房屋
# 装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。
#
# 给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。
#
# 示例 1:
#
# 输入: [2,3,2]
# 输出: 3
# 解释: 你不能先偷窃 1 号房屋(金额 = 2),然后偷窃 3 号房屋(金额 = 2), 因为他们是相邻的。
#
#
# 示例 2:
#
# 输入: [1,2,3,1]
# 输出: 4
# 解释: 你可... |
# 给定一个整数数组 nums,按要求返回一个新数组 counts。数组 counts 有该性质: counts[i] 的值是 nums[i] 右侧小于 num
# s[i] 的元素的数量。
#
# 示例:
#
# 输入: [5,2,6,1]
# 输出: [2,1,1,0]
# 解释:
# 5 的右侧有 2 个更小的元素 (2 和 1).
# 2 的右侧仅有 1 个更小的元素 (1).
# 6 的右侧有 1 个更小的元素 (1).
# 1 的右侧有 0 个更小的元素.
#
# Related Topics 排序 树状数组 线段树 二分查找 分治算法
# leetcode submit region begin(Prohib... |
# 数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
#
#
#
# 示例:
#
# 输入:n = 3
# 输出:[
# "((()))",
# "(()())",
# "(())()",
# "()(())",
# "()()()"
# ]
#
# Related Topics 字符串 回溯算法
# leetcode submit region begin(Prohibit modification and deletion)
class Solution(object):
def gen... |
import re
from string import ascii_lowercase, digits
def has_upper(s, field_name):
msg = 'The {0} you entered cannot have uppercase letters.'.format(field_name)
if any([char.isupper() for char in s]):
return True, msg
return False, None
def has_nonalpha(s, field_name):
msg = 'The {0} you ent... |
'''
Time Complexity
Best : O(nlog(n))
Average : O(nlog(n))
Worst : O(nlog(n))
'''
def HEAP_SORT(A):
heap_size = BUILD_MAX_HEAP(A)
for i in range(len(A)-1, 1, -1):
A[0], A[i] = A[i], A[0]
heap_size -= 1
MAX_HEAPIFY(A, 0, heap_size)
def BUILD_MAX_HEAP(A):
heap_size = len(A)
for i in range(int(len(A)/2), -... |
#!/usr/bin/python3
"""
Queries the Reddit API.
Returns the number of subscribers for a given subreddit
If an invalid subreddit is given, the function should return 0.
"""
import requests
def number_of_subscribers(subreddit):
"""
Function queries the Reddit API and returns the number of subscribers
"""
... |
n = 10000
step = 1./(n-1)
iterations = 100
import matplotlib.pyplot as plt
dist = [1./n] * n
values = [0.] * n
for it in range(iterations):
value_action = []
cumulative_dist = [0.] * n
s = 0.
for i in range(n):
s += dist[i]
cumulative_dist[i] = s - dist[i] / 2.
for action in range(n):
val = 0.
val += cu... |
s = 'hi ' * 3 + 'hello ' * 3 + 'test ' * 2 + 'world ' * 3 # input("Please enter string: ")
words = {}
for word in s.split():
if word in words:
words[word] += 1
else:
words[word] = 1
# words[word] = words.get(word, 0) + 1
print(words)
max_cnt = 0
max_word = ''
for key, value in words.it... |
def iteratively_pow(num, exp):
res = 1
while exp > 0:
res *= num
exp -= 1
return res
print(iteratively_pow(2, 5))
def recursive_pow(num, exp):
# base case
if exp == 0:
return 1
# recursive case
return num * recursive_pow(num, exp - 1)
print(recursive_pow(2, 5)... |
x = 4
y = 0
i = input()
# print('Результат деления:', x / y)
try:
print('Результат деления:', x / y)
# except Exception as ex:
# pass
except ZeroDivisionError as ex:
print(ex)
except OverflowError:
pass
except FloatingPointError as ex:
pass
|
x = 0
if x == 0:
print('Yes')
else:
print('No')
print('Yes') if x == 0 else print('No')
print('No') if x else print('Yes')
print('No' if x else 'Yes')
# x / y = z
y = 56
z = (x / y if y else x)
|
"""
class <NAME>(<Base class>):
pass
"""
class Point:
X = 5
Y = 8
def __init__(self, x, y):
self.x = x
self.y = y
def get_x(self):
return self.x
def get_y(self):
return self.y
def set_x(self, x):
self.x = x
def set_y(self, y):
self.... |
# Lab Topic 04-Flow control if elif and else
# Author: Andrew Beaty
# Practice Work by Sheila Bambrick
number = int(input("enter an integer:"))
if (number % 2) == 0:
print ("{} is an even number".format(number))
else:
print("{} is an odd number".format (number))
|
from tkinter import *
import random
def startGame():
boardWidth = 30
boardHeight = 30
tilesize = 10
class Snake():
def __init__(self):
self.snakeX = [20, 20, 20]
self.snakeY = [20, 21, 22]
self.snakeLength = 3
self.key = "w"
... |
# MATH10222, orbital motion for an inverse square central field.
# This computes the solution of Newton's second law directly.
# Initial conditions r=d, r-dot=0, theta=0
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as integrate
import matplotlib.animation as animation
import math
# graph ra... |
import pyperclip
import random
import string
class Credential:
"""
Class that generates new instances of user credentials
"""
credential_list = []
def __init__(self, account_name, account_email, account_password):
'''
__init__ method that helps us define properties for our objects... |
"""CPU functionality."""
import sys
import operator
class CPU:
"""Main CPU class."""
#load immediate (save the value)
#constructing cpu and other functions
def __init__(self):
self.ram = [0] * 256 # 256 bytes of memories
self.reg = [0] * 8 # 8 registe... |
def queryHandling():
locations = [[(1,2),(2,1),(3,3)],[(1,9),(3,8),(2,4)]]
#items = [(6,2),(9,3),(10,5)]
i = 0
k = 0
itemQuery = int(raw_input("Enter the item you wish to query: "))
#location is the array of different locations
#locations is the singular location
#items is the different ... |
class Contact:
contacts = []
next_id = 1
def __init__(self, first_name, last_name, email, note):
self.first_name = first_name
self.last_name = last_name
self.email = email
self.note = note
self.id = Contact.next_id
Contact.next_id += 1
@classmethod
... |
# -*- coding: utf-8 -*-
from collections import Counter, defaultdict
from itertools import product
from operator import itemgetter
MAX_SENTENCE = 3
class AutoCompleteSearch(object):
def __init__(self) -> object:
self.sentences = []
def create_counter(self, sentences):
"""
Create Cou... |
''' A PALINDROME IS STRING WHICH IS SAME IF REad from start or end
'''
word = input("Enter a word : ")
reverse = word[::-1]
if reverse == word:
print("Is palindrome"
else:
print("Not Palindrome")
=-------------------------------------------------------------------------------------... |
# coding=utf-8
from random import randint
def roll_dice(n=2):
"""
摇色子
:param n: 色子个数
:return: n颗色子点数之和
"""
total = 0
for _ in range(n):
total += randint(1,6)
return total
def add(a=0,b=0,c=0):
return a+b+c
# 如果没有指定参数那么使用默认值摇两颗色子
print(roll_dice())
# 摇三颗色子
print(roll_dic... |
"""
for循环实现100内的偶数求和
version 0.1
author lql
"""
sum = 0
for x in range(0,100,2):
sum = sum+x
print(sum)
"""
另外一种实现方式
"""
sum = 0
for x in range(1,100):
if x%2 ==0:
sum +=x
print(sum) |
class Node:
def __init__(self, data):
self._data = data
self._nextNode = None
@property
def data(self):
return self._data
@property
def nextNode(self):
return self._nextNode
@nextNode.setter
def nextNode(self, v):
self._nextNode = v
class LinkedLi... |
def main():
with open("input.txt", "r") as f:
lines = f.readlines()
first_wire_moves, second_wire_moves = [line.split(",") for line in lines]
first_current_point = (0, 0)
first_wire_points = []
second_current_point = (0, 0)
second_wire_points = []
for move in first_wire_moves:
... |
a=int(input("enter the number whichg has to be square :"))
for i in range (1,a):
b=(i*i)
print(b) |
adj=['red','big','tasty']
fruits=['apple','banana','cherry']
for x in adj:
for y in fruits:
if y=="banana" and x=='red':
continue
print(x,y) |
year=int(input("enter the year:"))
if (year%4==0) and (year%100!=0) or (year%400==0):
print('leap year')
else:
print('not a leap year') |
n=int(input("nhập n: "))
d=dict()
for i in range(1,n+1):
d[i]=i*i
print(d)
|
list = [i for i in input()]
cup1 = 1
cup2 = 0
cup3 = 0
for x in range(len(list)):
if list[x] == "A":
if cup1 == 1:
cup1 = 0
cup2 = 1
elif cup2 == 1:
cup1 = 1
cup2 = 0
elif list[x] == "B":
if cup2 == 1:
cup2 = 0
c... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def __init__(self):
self.res = 0
def pathSum(self, root: TreeNode, sum: int) -> int:
... |
"""
https://leetcode-cn.com/problems/number-of-provinces/solution/python-duo-tu-xiang-jie-bing-cha-ji-by-m-vjdr/
并查集是一种数据结构:
并查集这三个字,一个字代表一个意思。
1.并(Union),代表合并
2.查(Find),代表查找
3.集(Set),代表这是一个以字典为基础的数据结构,它的基本功能是合并集合中的元素,查找集合中的元素
并查集的典型应用是有关连通分量的问题
并查集解决单个问题(添加,合并,查找)的时间复杂度都是O(1)O(1)
因此,并查集可以应用到在线算法中
并查集的实现:
... |
"""
迭代法:
"""
class Solution:
def subsets(self, nums):
res = [[]]
for i in nums:
res = res + [[i] + num for num in res]
return res
# print(Solution().subsets([1, 2, 3]))
"""
递归:回溯
"""
class Solution1:
def subsets(self, nums):
res = []
... |
"""
暴力解法
"""
class Solution:
def exchange(self, nums):
res1 = []
res2 = []
for i in nums:
if i % 2 == 1:
res1.append(i)
if i % 2 == 0:
res2.append(i)
return res1 + res2
"""
双指针解法
"""
class Solution1:
def... |
'''
滑动窗口:
思路:
这道题主要用到思路是:滑动窗口
什么是滑动窗口?
其实就是一个队列,比如例题中的 abcabcbb,进入这个队列(窗口)为 abc 满足题目要求,当再进入 a,队列变成了 abca,
这时候不满足要求。所以,我们要移动这个队列!
如何移动?
我们只要把队列的左边的元素移出就行了,直到满足题目要求!
一直维持这样的队列,找出队列出现最长的长度时候,求出解!
时间复杂度:O(n)O(n)
'''
def lengthOfLongestSubstring(s):
if not s:
return 0
left = ... |
class Solution:
def wordBreak(self, s, wordDict):
if len(wordDict) == 0:
return False
l = len(s)
dp = [False for i in range(l + 1)]
dp[0] = True
for i in range(l):
for j in range(i + 1, len(s) + 1):
if (dp[i] and s[i:j] in word... |
def letterCombinations(digits):
if not digits:
return []
digit2chars = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz'
}
res = [i for i in digit2chars[digits[0]]]
... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
if not A and not B:
return True
if not A or ... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def pathSum(self, root: TreeNode, target: int):
path = []
tmp = []
def helper(root, target):
if... |
"""
暴力枚举:超时
"""
class Solution:
def findContinuousSequence(self, target: int):
i = 1
nums = []
result = []
while i < target:
nums.append(i)
i += 1
for i in range(len(nums) // 2):
for j in range(i, len(nums)):
... |
class Solution:
def groupAnagrams(self, strs):
dic = {}
for i in strs:
tmp = tuple(sorted(i))
dic[tmp] = dic.get(tmp, []) + [i]
res =[]
for i in dic:
res.append(dic[i])
return res
print(Solution().groupAnagrams(["eat", "tea", ... |
"""
暴力超时
"""
class Solution:
def myPow(self, x: float, n: int) -> float:
res = 1
if x > 0:
for i in range(n):
res *= x
return res
elif x == 0:
return 0
else:
x = -x
for i in range(n):
... |
class Solution:
def merge(self, left, right):
tmp = []
len1 = len(left)
len2 = len(right)
i, j = 0, 0
while i < len1 and j < len2:
if left[i] > right[j]:
self.res += (len1 - i)
tmp.append(right[j])
j += 1
... |
class Solution:
def hammingWeight(self, n: int) -> int:
res = bin(n)
return res.count('1')
"""
>> 和 <<都是位bai运算,对二进制数进行移位操作。
<< 是左移,末位补0,类比十进制数在末尾添0相当于原数乘以10,x<<1是将x的二进制表示左移一位,相当于原数x乘2。比如整数4在二进制下是100,
4 << 1左移1位变成1000(二进制),结果是8。
>>是右移,右移1位相当于除以2。
而>>=和<<=,就是对变量进行位运算移位之后的结果再赋值给原来的变量,可以类... |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
#
#
# @param head ListNode类
# @param n int整型
# @return ListNode类
#
class Solution:
def removeNthFromEnd(self, head, n):
# write code here
p = head
cnt = 0
while p:
... |
"""
暴力解法:超出时间限制
"""
def maxArea(height):
max_area = 0
for i in range(len(height) - 1):
for j in range(i+1, len(height)):
a = height[i:j+1]
print(a)
s = min(a[0], a[len(a)-1])
cur_area = s * (j-i)
if cur_area > max_area:
... |
# encoding: UTF-8
"""
Module to perform HTTP requests. To do so:
import http1
response = http1.request('http://www.google.com')
print(f'Status: {response.status} ({response.message})')
print(f'Headers: {response.headers}')
print(f'Body: {response.body.strip()}')
"""
import base64
from urllib.parse import... |
#!/usr/bin/env python3
# -*- encoding = utf-8 -*-
# 该代码由本人学习时编写,仅供自娱自乐!
# 本人QQ:1945962391
# 欢迎留言讨论,共同学习进步!
# 装饰器实例1---通过装饰器装饰打印效果
# def outer(fun):
# def inner():
# print("inner is start")
# fun()
# print("inner is done")
# return inner
#
#
# @outer # --> name = outer(name)
# def name... |
#!/bin/python3
"""
Monica wants to buy exactly one keyboard and one USB drive from her favorite
electronics store. The store sells n different brands of keyboards and m
different brands of USB drives. Monica has exactly s dollars to spend, and she
wants to spend as much of it as possible (i.e., the total cost of her pu... |
#!/bin/python
"""
Alice is taking a cryptography class and finding anagrams to be very useful.
We consider two strings to be anagrams of each other if the first string's
letters can be rearranged to form the second string.
In other words, both strings must contain the same exact letters in the same
exact frequency For... |
n = int(input('insira um número: '))
if n > 0:
print('É positivo')
else:
print('É negativo') |
#Faça um Programa que peça dois números e imprima a soma.
n1 = int(input("n1: "))
n2 = int(input("n2: "))
print(n1 * n2) |
import os
import csv
totalmonths = 0
net = 0
monthlychange = []
months = []
greatest_increase = 0
greatest_increase_month = 0
greatest_decrease = 0
greatest_decrease_month = 0
csvpath = os.path.join('.', 'Resources', 'budget_data.csv')
with open(csvpath, newline='') as csvfile:
csvreader = csv.rea... |
def encrypt(text,key):
result=""
for i in range(len(text)):
char = text[i]
if char==" ":
result+=" "
continue
if char.isupper():
result+=chr((ord(char)+key-65)%26 +65)
else:
result+=chr((ord(char)+key-97)%26 +97)
return result
def decrypt(ciphertext,key):
result=""
for i in range(len(ciphertex... |
# file to plot different graphs for the MLP model
import os
import numpy as np
import matplotlib.pyplot as plt
def plot_training_loss(hyperparameters, loss_curves, hyperparameter_type):
"""
Function to plot loss curves for MLP, for different activation functions
:param hyperparameters: a list of hyperpara... |
import numpy as np
import pandas as pd
def import_and_process(fname, input_cols=None, target_col=None):
"""
Imports a dataset, pre-processes it and splits it into train and test parts.
:param fname: Filename/path of data file.
:param input_cols: List of column names for the input data.
:param tar... |
Fahrenheit = float(input("Quantos graus Fahrenheit: "))
Celsius = (Fahrenheit - 32) / 9
print(Fahrenheit, " graus Fahrenheit são iguais a ", Celsius, " graus celsius")
|
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 5 19:31:21 2020
@author: Christoffer
"""
import os
import json
def remove(listobj):
cnt = 0
objectList = []
for elements in listobj:
if elements == " {\n":
objectList.append(cnt)
if elements == " },\n" or elements == " }\n":
... |
# Convolutional Neural Network
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.preprocessing.image import ImageDataGenerator
# Initialising the CNN
classifier = Sequential()
# S... |
#Inputting user information
argument = True
container = []
while argument:
x = input("Enter first name:")
y = input("Enter last name:")
z = input("Enter email:")
info = {'first name': x, 'last name': y, 'email': z}
#Generating the random password
import string
import random
(str... |
class LinkedListNode:
def __init__(self, value, nextNode = None):
self.value = value
self.nextNode = nextNode
class LinkedList:
def __init__(self, head = None):
self.head = head
def insert(self, value):
node = LinkedListNode(value)
if self.head is None:
... |
from functools import lru_cache
@lru_cache(maxsize=10000)
def Fibonacci(n):
if n == 1:
return 1
elif n == 2:
return 1
elif n > 2:
return Fibonacci(n - 1) + Fibonacci(n - 2)
valid = True
number = 0
while valid:
number += 1
if 10 > Fibonacci(number) / 10 **... |
import math
def is_prime_num(num):
sq = int(math.sqrt(num))
for j in range(2, sq):
if num % j == 0:
return False
return True
def if_Pandigital_number(num):
l_digits = []
str_num = str(num)
c = 0
for digit in str_num:
if digit in l_digits:
... |
#!/usr/bin/python3
#Filename:continue.py
while True:
s = input("enter something:")
if s == "quit":
break
elif len(s) < 3:
print("short")
continue
print("length is OK")
print("loop is over")
|
#!/usr/bin/python3
#Filename:func_return.py
def maximum(x, y):
if(x > y):
return x
else:
return y
x = int(input("x = "))
y = int(input("y = "))
val = maximum(x, y)
print(val)
|
#!/usr/bin/python3
#Filename:if.py
number = 23
guess = int(input("Enter number:"))
if(guess == number):
print("Congratulation you guess it!")
print("(But you can\'t get any prizes)")
elif(guess < number):
print("it is higher than that")
else:
print("it is lower than that")
print("Done")
|
#!/usr/bin/python3
#Filename:method.py
class Person:
def __init__(self, name):
self.name = name
def sayHi(self):
print("Hello %s" %self.name)
p = Person('Allen')
p.sayHi()
|
#!/usr/bin/python3
#Filename:expression.py
length = 5
breadth = 2
area = length * breadth
print("the area is",area)
print("perimeter is",2 * (length + breadth))
|
#The next line of code imports the whole Tkinter module
from tkinter import *
root = Tk()
class robotPosition():
def __init__(self, location):
self.label = location
location.bind('<ButtonPress-1>', self.StartMove)
location.bind('<ButtonRelease-1>', self.StopMove)
self.p... |
# -*- coding: utf-8 -*-
"""
Created on Mon May 11 08:11:49 2020
@author: Harshal
"""
t=int(input())
for i in range(t):
n=int(input())
a=n//2
if a%2==1:
print("NO")
else:
print("YES")
odd=[]
even=[]
for i in range(2,n+1,2):
... |
import sqlite3
class Money():
def __init__(self):
self.connection = sqlite3.connection(users.db)
self.cursor = self.connection.cursor()
def get_account(self):
query = "SELECT * FROM users WHERE account_number = {}".format(account_number)
self.cursor.execute(query)
money = self.cursor.fetchall()
return m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.