text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python
import argparse
# Create a parser object and add the arguments that are part of the program
parser = argparse.ArgumentParser(description='Read in some entries and add them.')
parser.add_argument('a', metavar='float_1', type=float, help='a float')
parser.add_argument('b', metavar='float_2', type... |
#!/usr/bin/env python3
# coding=utf-8
import re
while True:
print('Enter passwd to check: ')
passwd = input()
# chek passwd length
if passwd == '' or (len(passwd)) < 8:
print('password is not null or password length small then 8')
break
if re.search("[\d{8}]", passwd):
prin... |
"""If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000."""
x = 0
for n in range(1000):
if ((n % 3) == 0) or ((n% 5) ==0):
x += n
print "Adding " + str(n) + "\n"
... |
"""Utility functions used in at least 2 exercises"""
import math
def count_factors(number):
x = int(math.sqrt(number)) + 2
factor_count = 0
while x > 1:
if (number % x) == 0:
factor_count += 1
x -= 1
return factor_count
def is_prime(number):
if number == 2:
ret... |
import unittest
from Tweet import Tweet,TweetUser
class TestStringMethods(unittest.TestCase):
def test_create_user(self):
user=TweetUser("TestUser")
self.assertEqual(user.Name, 'TestUser')
def test_add_follower(self):
user1=TweetUser("TestUser1")
user2=TweetUser("Test... |
cars = ['audi', 'bmw', 'subaru', 'toyota']
#if 条件使用
for car in cars:
if car == "bmw":
print(car.upper())
else:
print(car)
#数字比较
age = 18
if 20 > age:
print("more than age", age)
else:
print("null")
#使用多个条件 and
if age >= 17 and age <=20:
print("17<=age<=20")
else:
print("null"... |
dimensions = (200, 50, 200, 300, 412)
for dimension in dimensions:
print(dimension)
dimensions = (1, 2, 5, 1, 7, 8)
print(dimensions)
#可以是不同类型
tuples = ("a", 1, 5, "fdjs", "9", 6)
for v in tuples:
print(v) |
#二叉树
#pip install binarytree
from binarytree import tree, build, Node, bst
#t = build([2, 5, 8, 3, 1, 9, 10, 13, 6, 7, 34, 19, 23, 45, 31, 24])
t = build([2, 5, 8, 3, 1, 9, 10, 13, 14, 12])
print(t)
# 求二叉树节点个数
def GetNodeNum(t):
if t == None:
return 0
left = GetNodeNum(t.left)
right= GetNode... |
# 二叉搜索树转换成双向链表
from binarytree import Node
# 打印,直接用binarytree打印会出错
def Print(t):
while t != None:
print(t.value, end='->')
t = t.right
print()
# 思路:中序遍历,缓存下上一个节点的指针
def convert(t, preNode):
if t == None:
return None
convert(t.left, preNode)
# 调整指针,左指针指向上一个节点,上一个节点的右指针指向当前... |
# 层次遍历二叉树
from binarytree import tree
def TreeLevelView(t):
if t == None:
return None
qu = []
qu.append(t)
while len(qu) != 0:
t = qu.pop(0)
print(t.value, end = ', ')
if t.left != None:
qu.append(t.left)
if t.right != None:
qu.append(t... |
#链表反转
class Node:
def __init__(self, value, next = None):
self.value = value
self.next = next
def list_reverse(head):
if head is None or head.next is None:
return head
p, q = head, head.next
head.next = None
while q:
tmp = q.next
q.next = p # 调换指针方向
... |
#链表反转
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def list_reverse(head):
if head == None or head.next == None:
return head
q, p = head, head.next
head.next = None
while p:
tmp = p.next
p.next = q
q = ... |
#旋转数组查找默认升序
# 思路:旋转数组取中间位置至少有一边是有序的,利用有序快速判断key在那一边,有序的
# 部分可以快速用二分查找定位
def Search(arr, key):
if len(arr) == 0:
return -1
beg, end = 0, len(arr) - 1
while beg <= end:
mid = (beg + end) // 2
cur = arr[mid]
if cur == key:
return cur
#默认升序,左边有序
... |
#跳台阶问题
# 首先考虑最简单的情况。如果只有1级台阶,那显然只有一种跳法。如果有2级台阶,那就有两种跳的方法了:一种是分两次跳,每次跳1级;另外一种就是一次跳2级。
# 现在我们再来讨论一般情况。我们把n级台阶时的跳法看成是n的函数,记为f(n)。
# 当n>2时,第一次跳的时候就有两种不同的选择:
# 一是第一次只跳1级,此时跳法数目等于后面剩下的n-1级台阶的跳法数目,即为f(n-1);
# 另外一种选择是第一次跳2级,此时跳法数目等于后面剩下的n-2级台阶的跳法数目,即为f(n-2)。
# 因此n级台阶时的不同跳法的总数f(n)=f(n-1)+f(n-2)。
def Fibonacci(n):
if n ==... |
#两个有序链表合并
import list_common as List
# 思路1:递归
def MergeSortList(l1, l2):
if l1 == None:
return l2
if l2 == None:
return l1
# 正向排序
cur = None
if l1.value < l2.value:
cur = l1 #cur串联l1节点
cur.next = MergeSortList(l1.next, l2) #串联下一个节点
else:
cur = l2
... |
#两个链表的第一个公共节点
#思路:先计算两个链表长度,然后算差值k,长的链表先走k步
import list_common as List
def GetLength(l):
if l == None:
return 0
cur, cout = l, 0
while cur:
cout += 1
cur = cur.next
return cout
def FindCommonNode(l1, l2):
if l1 == None or l2 == None:
return None
length1 = ... |
#list基础组件
def Print(head):
cur = head
while cur != None:
print('{}->'.format(cur.value), end='')
cur = cur.next
print()
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next |
def append(self, after_val, val):
# Input => (3->6->1->7->2->None, 6, 4)
# Output => 3->6->4->1->7->2->None
runner = self.head
while runner is not None:
if runner.val == after_val:
next_node = runner.next
runner.next = Node(val)
... |
# 编写一个程序判断给定的数是否为丑数。
# 丑数就是只包含质因数 2, 3, 5 的正整数
import time
class Solution():
def __init__(self, num):
self.num = num
def fun_one(self, num):
for x in [2,3,5]:
if self.num % x == 0:
self.num /= x
Solution.fun_one(self,num)
if self.num == 1... |
print("Give me two numbers and I will tell you the first number power the second number. First, give me the number that you want to find the power of.")
a=int(input())
print("Now give me the power that you want it to.")
b=int(input())
print(a, "power", b, "is", a**b, end="")
print(".")
|
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 8 03:17:24 2021
@author: mvjoshi
"""
print("Give me two numbers and I will tell you if all the 3n+1's of the numbers between those numbers reach a smaller number. Smaller number first:")
small_number=int(input())
print("Now larger number please:")
large_number... |
from math import sqrt
print("Give me two numbers 'a' and 'b' and I will tell you all the numbers up to 'a' that are not divisible by any number power 'b'. First, give me 'a'.")
a=int(input())
print("Now, give me 'b'.")
b=int(input())
print("The such numbers are written below.")
c=0
f=0
prime_list=[2]
while c**b<=a:
... |
print("Give me a number and I will tell you the puppies and kittens puzzle bad number groups up to it.")
upto_number=int(input())
tried_list=[]
used_list=[]
numbers_in_used_list=0
first_number=1
second_number=2
print(first_number, ",", second_number)
tried_list.append(first_number)
used_list.append(second_number)
numbe... |
print("Give me a word and then give me a such part and I will tell you how many times it occurs in the word. First, give me the word.")
a=input()
print("Now, give me the part.")
b=input()
c=len(b)
word_groups_list=[]
for i in range((len(a)-c)+1):
word_groups_list.append(a[i:(i+c)])
j=0
for k in range(len(word_grou... |
print("Give me x and y and I will tell you x in base y. First, give me x.")
x=int(input())
print("Now, give me y.")
y=int(input())
numbers_list=[]
print(x, "in base", y, "is", end=" ")
while x>0:
numbers_list.append(x%y)
x=x//y
for i in range(len(numbers_list)):
print(numbers_list[len(numbers_list)-i-1], en... |
#!/usr/bin/python3
print ("Give me a number and I will tell you if it is prime or composite and if itx2+1 is prime or composite.")
n=float(input())
if n%1==0:
j=0
i=2
if n>1:
while i*i<=n:
if n%i==0:
if i==n/i:
print ("It is composite. It is divisible ... |
# importing PyPDF2 module for extracting text from PDF files.
from PyPDF2 import PdfFileReader
# open the PDF file
# make sure the pdf file is in the same directory
# if the file is present in some other directory then one can provide the file path
pdfFile = open('pdf-file-name.pdf', 'rb')
# create PDFFileReader obj... |
def search(a,l,h):
m=(l+h)//2
if l>h:
return None
if a[m]>a[m+1] and a[m]>a[m-1]:
return a[m]
if a[m]>a[m+1] and a[m]<a[m-1]:
search(a,l,m)
if a[m]<a[m+1] and a[m]>a[m-1]:
search(a,m,h)
def main():
a=input('enter the sequence of numbers ')
a=a.split()
for i in range(len(a)):
a[i]=int(a[i])
print... |
"""
Decodes a string of binary text into ascii.
Works with both 7 and 8 bit ascii.
Matthew Tilton
2017-03-25
"""
import sys
BIN_TO_DECODE = sys.stdin.readlines()[0]
def decode():
"""
Decodes a string of binary text into ascii
"""
is_7_bit_ascii = (len(BIN_TO_DECODE) % 7 == 0)
is_8_bit_ascii = ... |
import sys
bintodecode = input()
result = ''
i = 0
def checksevenbit():
global bintodecode
global result
global i
firstseven = bintodecode[i:i+7]
try:
integer = int(firstseven, 2)
except:
integer = 32
character = chr(integer)
if character.isdigit() or character == ' ':
... |
# Valid Sudoku
# Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules
# http://sudoku.com.au/TheRules.aspx .
# The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
# 填充数独里面的数字,空单元格用 ',' 填充
# 为了便于计算 我直接改成了0
# 5 3 0 0 7 0 0 0 0
# 6 0 0 1 9 5 0 0 0
# 0 9 ... |
import pandas as pd
from can_tools.scrapers.base import DatasetBaseNoDate, InsertWithTempTableMixin
BASEURL = "https://www.census.gov"
DATEURL = "https://www.census.gov/econ/bfs/csv/date_table.csv"
class CensusBFS(InsertWithTempTableMixin, DatasetBaseNoDate):
"""
The Business Formation Statistics (BFS) are ... |
import random
# random.random() 获取0~1之间的随机小数
# 返回一个0~1之间的随机小数
num1 = random.random()
print('num1 =', num1)
# random.choice(序列)
# 随机返回序列中的某个值
list1 = [i for i in range(0,10)]
print('list1 = ', list1)
num2 = random.choice(list1)
print('num2 =', num2)
# random.shuffle(列表)
# 随机打乱列表
# 返回值为None
random... |
'''
讨论
一般来讲,创建一个多值映射字典是很简单的。但是,如果你选择自己实现的话,
那么对于值的初始化可能会有点麻烦,你可能会像下面这样来实现:
'''
from collections import defaultdict
d1 = {}
pairs =[
['a',[1,2,3]],
['b',['a','b','c']]
]
for key, value in pairs:
if key not in d1:
d1[key] = []
d1[key].append(value)
print(d1)
# 如果使用 d... |
'''
问题
你想构造一个字典,它是另外一个字典的子集。
解决方案
最简单的方式是使用字典推导。比如:
'''
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
tech_names = {'AAPL', 'IBM', 'HPQ', 'MSFT'}
new_prices1 = {key:value for key,value in prices.items() if value > 200}
new_prices2 = {key:va... |
import threading
import time
# help(threading.Thread)
# 类继承自threading.Thread
class MyThread(threading.Thread):
def __init__(self, arg):
super(MyThread, self).__init__()
self.arg = arg
# 必须重写run函数,run函数代表的是真正执行的功能
def run(self):
time.sleep(2)
print('The args for this class is {0}'.format(self... |
# #str()返回一个用户易读的字符串,repr()返回一个计算器易读的字符串
# str1 = 'hello world'
# print(str(str1))
# print(repr(str1))
# #输出格式美化、
# #rjust()函数使字符串靠右对齐,在左边补齐空格,还有类似的方法ljust(),center(),
# #这些函数只会补齐空格不会添加其他内容
# #zfill()函数会在数字的左边补齐0
# #输出一个平方立方表
# for x1 in range(1,11):
# print(repr(x1).rjust(4), repr(x1*x1).rjust(4), end=" ")
... |
import re
str1 = "hello 123 hello 456 hello 789"
p = re.compile(r'([a-zA-Z]+) ([0-9]+)')
# help(p.sub)
# Help on built-in function sub:
# sub(repl, string, count=0) method of _sre.SRE_Pattern instance
# Return the string obtained by replacing the leftmost non-overlapping
# occurrences of pattern... |
'''
另外一种方式是使用 operator.attrgetter() 来代替 lambda 函数:
讨论
选择使 用 lambda 函数或者 是 attrgetter() 可能取决 于个人 喜好。但是,
attrgetter() 函数通常会运行的快点,并且还能同时允许多个字段进行比较。这
个跟 operator.itemgetter() 函数作用于字典类型很类似(参考 1.13 小节)。例如,
如果 User 实例还有一个 first_name 和 last_name 属性,那么可以向下面这样排序:
by_name = sorted(users, key=attrgetter('last_name', 'firs... |
'''
在定义正则式的时候,通常会利用括号去捕获分组。比如:
'''
import re
pattern = re.compile(r'(\d+)+/(\d+)+/(\d+)')
text1 = '11/22/2018'
text2 = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
result1 = pattern.match(text1)
# result2 = pattern.findall(text)
print(result1)
print(result1.group(0))
print(result1.group(1))
prin... |
"""
处理指定路径下的图片
可以指定处理后的尺寸
"""
from PIL import Image
import os
# import sys
def input_file_name(file_path, file_name, file_list):
"""输入要进行操作的文件"""
if file_name in file_list:
handle_image()
return "处理成功"
else:
return "该文件不存在!"
def read_file_path(file_path):
"""读取文件夹,显示文件夹内容"""
file_list = os.listdir(file... |
## 3. 多态
#### - 多态就是同一个对象在不同情况下有不同的状态出现
#### - 多态不是语法,是一种设计思想
#### - 多态性:一种调用方式, 不同的执行效果
#### - 多态:同一事物的多种形态,动物分为人类,狗类....
## MiXin设计模式
#### - 主要采用多继承的方式对类的功能进行扩展
#
## 使用Mixin类实现多重继承要非常小心
#### -首先它必须表示某一种功能,而不是某个物品,如同Java中的Runnable,Callable等
#### -其次它必须责任单一,如果有多个功能,那就写多个Mixin类
#### -然后,它不依赖于子类的实现
#### -最... |
# coding:utf-8
"""
二叉树的实现
深度优先遍历
- 先序遍历
- 中序遍历
- 后序遍历
02.py递归实现
03.py栈实现
"""
class Node(object):
"""树的节点"""
def __init__(self, item):
self.item = item
# 左右子节点
self.lchild = None
self.rchild = None
class BinaryTree(object):
"""二叉树"... |
import numpy
a = numpy.array([[1,2,3,4],
[5,6,7,8],
[9,10,11,12]])
b = numpy.array([1,2,3,4])
# 将b中的数据加到a上
# 1.使用for循环
for i in range(3):
a[i,0:4] += b
print("a:\n", a)
# 2.使用tile()函数
a = a + numpy.tile(b,(3,1))
print("a:\n", a)
# 3.直接相加
a = a+b
print("a:... |
import time
# 定义一个装饰器
def PrintTime(func):
def wrapper(*args, **kwargs):
print("Time:", time.ctime())
return func(*args, **kwargs)
return wrapper
# 使用一个装饰器
# 借助@语法糖
@PrintTime
def hello():
print("hello world!")
hello()
def func1():
print("This is func1!")
@PrintTime
def func2():
pr... |
# 访问一个网址
# 更改自己的UserAgent进行伪装
from urllib import request
url = 'http://www.baidu.com'
# 1.直接设置
# headers = {
# 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
# }
# # 也可以这样
# # headers = {}
# # headers['User-Agent'] = 'M... |
'''
解析xml文件
'''
from lxml import etree
def parse():
# 获取ElementTree
tree = etree.parse("test01.xml")
# print(tree)
# 获取根元素
root = tree.getroot()
print(root)
# get(attrib)可以获得指定属性值
print("root.name:", root.get("name"))
print("root.tag:{0}, root.attrib:{1}, root.text:{... |
import socket
def tcp_server():
ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 8888
addr = (host, port)
ss.bind(addr)
ss.listen(5)
while True:
conn, address = ss.accept()
print("链接地址:", address)
while True:... |
from collections import namedtuple
stu = namedtuple('Student', ['id', 'all_result', 'n'])
stu_info = [
('zyp', 300, 3),
('gzy', 250, 3),
('zy', 200, 3),
]
def Grade(stu_info):
# avg = 0
for info in stu_info:
avg = info[1]/info[2]
print(avg)
Grade(stu_info)
# 下标操作通常会让代码表意不清晰,... |
'''
ChainMap 对于编程语言中的作用范围变量(比如 globals , locals 等)是非常有
用的。事实上,有一些方法可以使它变得简单:
'''
from collections import ChainMap
values = ChainMap()
values['x'] = 1
values['y'] = 2
print(values)
# add a new mapping
values2 = values.new_child()
values2['x'] = 10
values2['y'] = 20
print(values2)
# add a new mappin... |
'''
利用time函数,生成两个函数
顺序调用
计算总的运行时间
'''
import time
def loop1():
print("start loop1 {}".format(time.ctime()))
time.sleep(5)
print("end loop1 {}".format(time.ctime()))
def loop2():
print('start loop2 {}'.format(time.ctime()))
time.sleep(3)
print("start loop2 {}".format(time.ctime()))
def main... |
# 喜欢的数字 :编写一个程序,提示用户输入他喜欢的数字,并使用json.dump() 将这个数字存储到文件中。
# 再编写一个程序,从文件中读取这个值,并打印消息“I knowyour favorite number! It's _____.”。
import json
# filename = input('please input filename:')
filename = 'filename.json'
with open(filename, 'w') as f:
number = input('input a number:')
json.dump(number, f)
with ... |
import re
# help(re.search)
# Help on function search in module re:
# search(pattern, string, flags=0)
# Scan through string looking for a match to the pattern, returning
# a match object, or None if no match was found.
p = re.compile(r'([a-z]+) ([a-z]+)')
# help(p.search)
# Help on built-in fun... |
'''
讨论
如果你仅仅就是想消除重复元素,通常可以简单的构造一个集合。比如:
然而,这种方法不能维护元素的顺序,生成的结果中的元素位置被打乱。而上面的
方法可以避免这种情况。
在本节中我们使用了生成器函数让我们的函数更加通用,不仅仅是局限于列表处
理。比如,如果如果你想读取一个文件,消除重复行,你可以很容易像这样做:
'''
a = [1, 5, 2, 1, 9, 1, 5, 10]
set_a = set(a)
print(set_a)
def dedupe(f):
set_f = set()
for line in f:
# print(line)
... |
'''
如果你想在一个集合中查找最小或最大的 N 个元素,并且 N 小于集合元素数量,
那么这些函数提供了很好的性能。因为在底层实现里面,首先会先将集合数据进行堆排
序后放入一个列表中
堆数据结构最重要的特征是 heap[0] 永远是最小的元素。并且剩余的元素可以很
容易的通过调用 heapq.heappop() 方法得到,该方法会先将第一个元素弹出来,然后
用下一个最小的元素来取代被弹出元素(这种操作时间复杂度仅仅是 O(log N),N 是
堆大小)。比如,如果想要查找最小的 3 个元素,你可以这样做:
当要查找的元素个数相对比较小的时候,函数 nlargest() 和 nsmallest() 是很
合... |
"""
TCP客户端
1.socket建立
2.发送消息到指定服务器(ip + port)
3.等待反馈
"""
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 客户端绑定端口号,如果不绑定则由系统自动分配
s.bind(('127.0.0.1', 6666))
text = '你好'.encode()
s.sendto(text, ('127.0.0.1', 9999))
data, addr = s.recvfrom(1024)
print("接收到来自{}的反馈... |
'''
如果你想检查多种匹配可能,只需要将所有的匹配项放入到一个元组中去,然后传
给 startswith() 或者 endswith() 方法:
'''
import os
filelist = os.listdir('f:/python/oop')
for filename in filelist:
print(filename)
match = ('.py', '.md')
new_list = [filename for filename in filelist if filename.endswith(match)]
for i in new_list:
print(i)... |
import threading
import time
def loop1(in1):
print("start loop1 {}".format(time.ctime()))
print('这是参数1{0}'.format(in1))
time.sleep(5)
print("end loop1 {}".format(time.ctime()))
def loop2(in1, in2):
print('start loop2 {}'.format(time.ctime()))
print('这是参数1{0},这是参数2{1}'.format(in1, in2))
time.sle... |
#while 循环
#python 中没有do...while循环
#用while循环求0到九十九相加之和
n = 0
sum1 = 0
while n < 100:
sum1 = sum1 + n
n = n + 1
print("sum1:",sum1)
#用for循环求0到99相加之和
m = 0
sum2 = 0
for m in range(0,100): #range()函数用于
sum2 = sum2 + m
print("sum2:",sum2)
#使用range()和len()函数遍历一个序列的索引
student1 = ['靳淑佳', '杨浩然', '陈世创', ... |
# 类的常用魔术方法
# 操作类:
# - 魔术方法就是不需要人为调用的方法,基本是在特定的时刻自动触发
# - 统一特征:方法名被前后个两个下划线包裹,最常用 __init__(self)
# - __call__ :在对象当函数使用时触发
# - __str__:当把对象当字符串使用时自动调用,返回一个字符串
# - __repr__: 返回字符串,跟__str__类似
# 描述符相关:
# - __set__:
# - __get__:
# - __delete__:
# 属性相关操作
# - __getattr__: 访问一个不存在的属性时触发
# - __s... |
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--start", help="first number")
parser.add_argument("--end", help="last number")
args = parser.parse_args()
x = int(args.start or 0)
y = int(args.end or 0)
sum =0
for n in range(x,y+1):
sum += n
print sum |
def divisibility(a,b):
if (a%b)==0:
return 0
else:
return(b-(a%b))
t=int(input())
for loop in range(t):
a,b=map(int,input().split())
print(divisibility(a,b))
|
import math
n = int(input("Ingrese el radio: "))
print("El área del circulo es: ", 3.1416* n**2) |
if(3 < 5): # <- Doppelpunkt
print("3 ist kleiner als 5") # Wichtig: Einrückung!
if(5 < 3):
print("5 ist kleiner als 3")
print("Eine zweite Zeile")
# Alle Operatoren == != <= >= < >
# Eingabe vom Benutzer einlesen
# "Zur Sicherheit" in int umwandeln
zahl = int(input("Eingabe: "))
# Testen auf Gleichheit und Ungle... |
nome = input ('Qual é o teu nome?')
idade = input ('Qual é a tua idade?')
peso = input ('Qual é o teu peso?')
print (nome, idade, peso)
|
from random import randint
import time
print('\033[1;4mDesafio 45 - GAME: Pedra, Papel e Tesoura\033[m')
print("""\033[1mCrie um programa que faça o computador jogar Jokenpô com você.\033[m""")
print('\033[1;35m♣\033[m'*60)
print(' \033[1;4mPEDRA, PAPEL E TESOURA\033[m')
print('\033[1;35m♣\033[m'... |
print('Desafio 78 - Maior e Menor valores na lista')
print('Faça um programa que leia 5 valores numéricos e guarde-os em uma lista. \nNo final, mostre qual foi o maior e o menor valor digitado e as suas respectivas posições na lista. ')
print('')
valores = []
menor = maior = 0
cont = 0
for cont in range(1, 6):
valo... |
print('Desafio 40 - Aquele clássico da Média')
print("""Crie um programa que leia duas notas de um aluno e calcule sua média, mostrando uma mensagem no final, de acordo com a média atingida:
- Média abaixo de 5.0: REPROVADO
- Média entre 5.0 e 6.9: RECUPERAÇÃO
- Média 7.0 ou superior: APROVADO""")
print('\033[1;35m~\03... |
print('\033[1;4mDesafio 51 - Progressão Aritmética\033[m')
print('\033[1mDesenvolva um programa que leia o primeiro termo e a razão de uma PA. No final, mostre os 10 primeiros termos dessa progressão.\033[m')
print('\033[1;35m=\033[m'*35)
print(' \033[1;4;36mOs 10 Primeiros Termos da PA\033[m')
print('\033[1;35m=\0... |
print('\033[1;4mDesafio 49 - Tabuada v.2.0\033[m')
print('\033[1mRefaça o DESAFIO 009, mostrando a tabuada de um número que o usuário escolher, só que agora utilizando um laço for.\033[m')
print(' ')
print('=-' * 10)
print(' TABUADA')
print('-=' * 10)
print(' ')
num = int(input('Digite um número: '))
print(' ')
fo... |
print('Desafio 34 - Aumentos múltiplos')
print("""Escreva um programa que pergunte o salário de um funcionário e calcule o valor do seu aumento.
Para salários superiores a R$1250,00, calcule um aumento de 10%. Para os inferiores ou iguais, o aumento é de 15%.""")
sal = float(input('Digite o valor do salário do funci... |
import random
print('\033[1;4mDesafio 20 - Sorteando uma ordem na lista\033[m')
import math
print('Um professor quer sortear a ordem de apresentação de trabalhos dos alunos. \nFaça um programa que leia o nome dos quatro alunos e mostre a ordem sorteada.')
a1 = input('Digite o nome do primeiro aluno: ')
a2 = input('Di... |
print('Desafio 39 - Alistamento Militar')
print("""Faça um programa que leia o ano de nascimento de um jovem e informe, de acordo com a sua idade,
se ele ainda vai se alistar ao serviço militar, se é a hora exata de se alistar ou se já passou
do tempo do alistamento. Seu programa também deverá mostrar o tempo que fal... |
print('\033[1;4mDesafio 7 - Média Aritmética\033[m')
nome = input('\033[34mNome do aluno:\033[m ')
print('\033[1;4mDigite abaixo as notas do aluno:\033[m')
port = int(input('\033[34mNota de Língua Portuguesa:\033[m '))
mat = int(input('\033[34mNota de Matemática:\033[m '))
media = (port+mat)/2
print('O aluno \033[3... |
print('\033[1;4mDesafio 56 - Analisador Completo\033[m')
print('\033[1mDesenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final do programa, mostre: a média de idade \ndo grupo, qual é o nome do homem mais velho e quantas mulheres têm menos de 20 anos.\033[m')
maior = 0
menor = 0
totidade = 0
nomeve... |
print('Desafio 83 - Validando Expressões Matemáticas')
print('Crie um programa onde o usuário digite uma expressão qualquer que use parênteses. Seu aplicativo deverá analisar \nse a expressão passada está com os parênteses abertos e fechados na ordem correta.')
print('')
print('\033[1m=\033[m'*40)
print(f'\033[1;35m{"... |
print('\033[1;4mDesafio 76 - Lista de Preços em Tuplas\033[m')
print('')
print('\033[1mCrie um programa que tenha uma tupla única com nomes de produtos e seus respectivos preços, na sequência. \nNo final, mostre uma listagem de preços, organizando os dados em forma tabular.\033[m')
print('')
print('\033[1m-\033[m'*51)
... |
# Задание 3
# По введенным пользователем координатам двух точек вывести уравнение прямой вида y = kx + b, проходящей через эти точки.
print("Задание 3")
a = input("Введите координаты точки А (x1,y1): ").split(",")
b = input("Введите координаты точки B (x2,y2): ").split(",")
x1 = int(a[0])
x2 = int(b[0])
y1 = int(a[1... |
#!/usr/bin/env python3
max_length = 5
def take_user_input():
"""
This function takes a user inputs, perform constraint checks and parses it
@:return list of parsed user input
"""
input_word = input("Please Enter a single letter or a string of letters from the English Alphabet")
checks_passed = ... |
import numpy as np
import datetime
## array [x:y] where x is index from which array needs to start and y is till
## when array is present
# Create numpy single dimention array
def create_1_dim_array():
a = np.array([1, 2, 3]) # Create a rank 1 array
#print(type(a)) # Prints "<class 'numpy.ndarr... |
# Basic boxplot of a single column.
### Magic line to make plots appear on notebook
%matplotlib inline
def boxplot(df,col):
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(9, 6))
ax = fig.gca()
df.boxplot(column = col, ax = ax)
ax.set_title('Box plot of ' + col)
ax.set_ylabel(col)
... |
# Çözüm - 1
numbers = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
odd_list = []
for i in range(len(numbers)):
if numbers[i] % 2 == 1:
odd_list.append(numbers[i])
odd_list.sort()
numbers[i] = "T"
counter = 0
for y in range(len(numbers)):
if numbers[y] == "T":
numbers[y] = odd_list[counter]
... |
# Vücut Kütle Endeksi Hesaplama
weight , height = float (input ("Please enter your weight (kg):")), float (input ("Please enter your height (meters):"))
bmi = weight/height**2 #Body_mass_index
print ("Your body mass index is :" + str (bmi))
if bmi < 18.5 :
print ( "You are Underweight")
elif 18.5 <= bmi <= 2... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
alien = {'color':'green','points':5,'start_position':0,'current_position':10}
# In[2]:
print(alien)
# In[3]:
# modify the values in dictionary
# In[4]:
alien['color'] = 'yellow'
# In[5]:
alien['points'] = 10
# In[6]:
print(alien)
# In[7]:
# delet... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
#@created: 14.09.2021
#@author: Marina Popova
class CoffeeMachine:
resources_name = ['water', 'milk', 'coffee beans', 'cups', 'money']
def __init__(self, w = 400, m = 540, cb = 120, c = 9, mn = 550):
self.resources = [w, m, cb, c, mn]
self.worka... |
def kaprekar(num) :
i = 0
while num not in [6174, 0] :
num = desc_digits(num) - asc_digits(num)
i += 1
return i
def breakdown_digits(num) :
digits = list(map(int, list(str(num))))
while len(digits) < 4 :
digits.append(0)
return digits
def largest_digit(num) :
return ... |
#Taken from https://www.reddit.com/r/dailyprogrammer/comments/7vm223/20180206_challenge_350_easy_bookshelf_problem/
#As noted in comments, this problem is actually NP-hard,
shelves = list(map(int, input("Enter shelf values: ").split()))
shelves.sort(reverse=True)
done = False
bookValues = [];
while not done :
l... |
from tkinter import *
window= Tk()
one=Label(window,text="one",bg="black")
one.pack()
two=Label(window,text="two",bg="blue")
two.pack(fill=X)
three=Label(window,text="three",bg="green")
three.pack(fill=Y,side=LEFT)
def left(event):
print("left")
def right(event):
print("right")
window.bind("<Butto... |
import math
def is_prime(n):
flg = True
for i in range(2, int(math.sqrt(n)+1)):
if n % i == 0:
flg = False
break
return flg
def P10():
sum = 0
for i in range(2,2000001):
if is_prime(i):
sum += i
return sum
print(P10())
|
#Objects used as structures for the TRAILS graph generator
#Cartesean coordinate
class Point(object):
def __init__(self,x,y):
self.x=1.0*x;
self.y=1.0*y;
class STP(object):
def __init__(self,user,pointsIndex,enterTime,exitTime):
self.user=user; #Trace user owner of t... |
#Functions and objects to process and represent traces
import os #Functions to create directories
import csv #Functions to create csv tables
import math #Mathematical functions
import matplotlib.pyplot as plt #Functions to plot graphs
#User... |
#!/usr/bin/python3
"""Divide a matrix"""
def matrix_divided(matrix, div):
"""function that divides all elements of a matrix"""
if not check_matrix(matrix):
raise TypeError("matrix must be a matrix\
(list of lists) of integers/floats")
for i in matrix:
if len(i) == len(matrix[0]):
... |
#!/usr/bin/python3
def print_matrix_integer(matrix=[[]]):
for i in matrix:
end = ""
for a in i:
print("{:s}{:d}".format(end, a), end="")
end = " "
print()
|
"""
function: 遍历目录,返回目录结构的 list
"""
import os
def scanpath(filepath, suffix):
file_list = []
print("开始扫描【{0}】".format(filepath))
if not os.path.isdir(filepath):
print("【{0}】不是目录".format(filepath))
exit(-1)
for filename in os.listdir(filepath):
if os.path.isdir(filepath + "... |
from collections import deque
def solution(priorities, location):
queue = deque(priorities)
answer = 0
while location >= 0:
left = queue.popleft()
location -= 1
check = False
for q in queue:
if(q > left):
check = True
bre... |
def solution(distance, rocks, n):
rocks.sort()
rocks.append(distance)
answer = 0
start, end = 1, distance # answer은 1 ~ distance 사이에 있음
while start <= end:
mid = (start + end) // 2
# 부서진 바위의 수 세기
cnt_rock, prev_rock = 0, 0
for rock in rocks:
... |
def solution(p):
if not p: return p
count = 0
is_correct = True
for i, pp in enumerate(p):
count += 1 if pp == '(' else -1
if count < 0:
is_correct = False
elif count == 0:
u, v = p[:i+1], p[i+1:]
if is_correct:
... |
from itertools import permutations
def prime_tf(number): #소수 판별
return all([(number%n) for n in range(2, int(number**0.5)+1)]) and number>1
def solution(numbers):
answer = 0
numbers=list(numbers)
prime_list=[]
for i in range(1, len(numbers)+1):
prime_list += list(map(int, map(''.join,... |
def count_divisible_numbers_less_than(n: int):
count = 0
for k in range(2, n+1):
not_prime = False
for i in range(2, k):
if k%i == 0:
not_prime = True
if not_prime:
count+=1
print(count) |
import numpy as np
u=np.array((3,4,5))
v=np.array((1,2,7))
print("vector u:",u)
print("vector v:",v)
print("enter a,b:")
a=int(input())
b=int(input())
d=(a*u)+(b*v)
print("vector for au+bv",d)
p=np.dot(u,v)
print("dot product:",p)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.