text stringlengths 37 1.41M |
|---|
# Str07.py
a1 = 'Welcome to Korea Education'
print(a1[0::2])
print(a1[-9:])
print(a1[-9::2]) # stride
print('abc' < 'abd')
print('a' < 'A')
print('가' > '황')
print(a1.startswith('We'))
print(a1.endswith('on'))
print(a1.upper())
print(a1.lower())
print('Korea' in a1)
print('Korea' not in a1)
print(a1.count('e'))
prin... |
class OneIndexedList(list):
"""
This class exists to hold data which is one-indexed.
It pads the zero index with None, and will behave incorrectly if this
pad is ever removed. Suggested use is append-only.
When iterating over this list, the first item will be discarded by the
iterator.
... |
# 给用户三次输入用户名和密码的机会,要求如下:
# 1)如输入第一行输入用户名为‘Kate’, 第二行输入密码为‘666666’,输出‘登录成功!’,退出程序;
# 2)当一共有3次输入用户名或密码不正确输出“3
# 次用户名或者密码均有误!退出程序。”。
def userPasswd():
num2 = 0
for i in range(0,3):
username = input('请输入... |
def asterisk_test(a, *args):
print(a, args)
print(type(args))
asterisk_test(1, 2, 3, 4, 5, 6)
# 1 (2, 3, 4, 5, 6)
# <class 'tuple'>
def asterisk_test(a, **kargs):
print(a, kargs)
print(type(kargs))
asterisk_test(1, b=2, c=3, d=4, e=5, f=6)
# 1 {'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
# <class ... |
'''
json和csv格式文件处理
'''
# 引入json模块
import json
import csv
#dumps和loads
json_dict = {"name":"zhangsan","age":20,"language":["python","java"],"study":{"AI":"python","bigdata":"hadoop"},"if_vip":True}
'''
json_str = json.dumps(json_dict) # 转换为json编码的字符串
print(json_str)
print(type(json_str))
python_data = json.loads(json_... |
'''
while循环
'''
# num = 1
# print(num)
# num += 1
# print(num)
# num = 1
# while num <= 10:
# print(num)
# num += 1
# 第一步打印倒三角形
# 1)行号和空格数相等
# 2)*号个数=7-行号*2
# i = 0
# while i < 4:
# print(" " * i, end = "")
# j = 0
# while j < 7 - i * 2:
# print("*" , end = "")
# j += 1
# pri... |
'''
函数使用
1.局部变量和全局变量
'''
# 局部变量: 函数内部定义的变量
# def set_name():
# name = "zhangsan"
# return name
# def get_name(name):
# name = "lisi"
# print(name)
# nm = set_name()
# get_name(nm)
# 全局变量
# 可以在不同的函数中使用
'''
name = "zhangsan"
def get_name():
print(name)
def get_name2():
print(name)
get_na... |
'''
for循环
'''
#打印0到9十个数字
# for i in range(0, 10):
# print(i)
#range(0,10):[0,1,2,3,4,5,6,7,8,9)
# for i in range(0,10):
# print(i)
#打印0到9的偶数
# for i in range(0,10):
# if i % 2 == 0:
# print(i)
# #range(0,10,2)=[0,2,4,6,8)
# for i in range(0,10,2): # 这里设置了步长是2
# print(i)
# break跳出for 循环
for... |
import pandas as pd
import numpy as np
_ = np.newaxis
# Add classes of HMM
# Finite
# Laplace
# Multivariate
class HMM:
def __init__(self, N=2):
"""
Create a Hidden Markov Model.
Parameters
----------
N : int, optional
Number of states of the Markov Mod... |
from itertools import cycle
import pdb
from box import Box
from player import Player, HumanPlayer
class Game:
win_conditions = [
[0,1,2], [3,4,5], [6,7,8],
[0,3,6], [1,4,7], [2,5,8],
[0,4,8], [2,4,6]
] # These are the lines!
def __init__(self, player1, player2):
self.boxes = []
for i in ran... |
import random
def no_generator_4digit():
return random.sample(range(10), 4)
def num_input(number="Enter a 4 digit number:"):
return list(input(number))
def play_cows_bulls():
cows = 0
bulls = 0
attempts = 0
while True:
player = num_input()
wining_num = no_generator_4digit(... |
#lab 11
#Student: Adnan Hafeez 101210710
#Exercise 1
#Step 1
#point1 = [1.0,2.0]
#point1
#What is displayed when Python evaluates point1?
#Python evalutes whats to the right of the equal sign, which is a list with two values. Two float objects are created 1.0,2.0
#respectively, and assigned to the list with index 0 a... |
import re
class Solution:
def isNumber(self, s: str) -> bool:
naturalNumberPattern = "((\+|\-)?([0-9]+|([0-9]*\.[0-9]+)|([0-9]+\.[0-9]*))){1}"
Integer = "(\+|\-)?[0-9]+"
eExperssion = "(e"+Integer+")?"
decimalNumber = naturalNumberPattern+eExperssion
finalExperssion = "(\s*"+... |
# Given a sorted array of integers, return the first and last
# indices of a target value in the array. If none exist, return
# [-1, -1]
# Solution
# Time complexity: Worst case O(log(n)) using binary search
# Space complexity: O(1) - not using an auxiliary data struct
def first_and_last(arr, target):
return([bin... |
# This inserts the random module which allows the computer to
# randomly chose something from a list.
import random
# This variable is to keep track of the number of correct answers the
# user has entered.
score = 0
# This is the program to create the question and generate the correct
# answer for that que... |
#Définition des fonctions
def dico_rempli(un_dico):
"""
"""
while True:
nom=input("Entrez le nom (ou <enter> pour terminer) : ")
if nom=="":
menu(un_dico)
break
age=int(input("Entrez l'âge (nombre entier !) : "))
taille=float(input("Entrez la taille (... |
class Unit(object):
def __init__(self, health, speed, hit_power):
self.health = health
self.speed = speed
self.hit_power = hit_power
def print_status(self, name='Unit'):
print(name, 'status:')
print('\tHealth: ', self.health)
print('\tSpeed: ', self.speed)
... |
#TBA
import time
class Time:
def __init__(self):
pass
def add_time(self):
"""adding time in our task"""
add_time = float(input("time to add: "))
return dt.timedelta(add_time)
def change_time(self, time):
"""changing time in task"""
time = dt.datetime.now()... |
mass_lb = int(input("What is your mass in pounds?" ))
mass_stone = mass_lb * 1 / 14
print "You weigh", mass_stone, "stone."
|
'''Each new term in the Fibonacci sequence is generated by adding the previous two terms.
By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.'''
f... |
#py_cubs_players.py
players={225:('Jake', 'Arrieta'),
234:('Jake', 'Buchanan'),
240:('Trevor', 'Cahill')
}
print(players)
players={"Arrieta": ("Jake", 225),
"arriETTA": ("Jake", 225),
"arrieta": ("Jake", 225),
}
"""
I just hired a new admin and it d... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 14 15:57:02 2016
#py_animal_class_v2.py
"""
from random import choice
class Animal:
tricks = ["jumping", "playing dead",
"rolling over", "walking backwards"]
def __init__(self, name, species, age, fav_food):
self.name = name
... |
#py_string_manipulation.py
seven_deadly=" avarice envy wrath sloth gluttony lust hubris "
#exists?
sin='eNvY' #this is weirdly formed (common "in the wild")
print("{} in there? {}\n".format(sin.lower(), sin.lower() in seven_deadly))
#doesn't exist?
print("try the key word not")
print("{} NOT in there? ... |
userInput = input("Enter a letter or symbol, il find the number in it's alphabet! For a Symbol you must hold down Opt+Shift and then a letter you want.")
alphabet = 'abcdefghiklmnopqrstuvwxyz'
symbol = '`⁄€‹›fifl‡°·‚—±»’”∏؈¨Áˇ‰´„ŒÅÍÎÏ˝ÓÔÒÚÆ¿˘¯Â˜ı◊Dz¸'
pos = alphabet.index(userInput)
pos = symbol.index(userInput)
prin... |
#IMPORTANT: GIVE MORE SPACE FOR THE CONSOLE SO THE GAME CAN PROPERLY DISPLAY
import time
print("Welcome to Conway's Game of Life. We start with a 30x60 grid of cells, either alive or dead. Here are the rules:\n\t1) Any live cell with fewer than two live neighbours dies, as if by underpopulation.\n\t2) Any live cell w... |
a1 = input("enter string: ")
n = input("enter n: ")
s= int(n)
a2 = a1[:s]
print (a2)
a3 = a1[s+1:]
print (a3)
finalstring = a2+a3
print (finalstring)
# s1= input("Enter first string:")
# s2= input("Enter second string:")
# if(sorted(s1) == sorted(s2)):
# print("The strings are anagrams.")
# else:... |
import pygame
# start pygame up
pygame.init()
# some constants
WIDTH = 1000
HEIGHT = 500
GAME_TITLE = "Snake Game"
FPS = 15
WHITE = (255, 255, 255)
# sprites
class Unit(pygame.sprite.Sprite):
def __init__(self, color, position, dimensions):
pygame.sprite.Sprite.__init__(self)
# set the image of... |
cnt = int(input())
nums = list(map(int, input().split(" ")))
min = nums[0]
max = nums[0]
for num in nums:
if num < min:
min = num
if num > max:
max = num
print(min,max)
|
"""
Count bits
"""
def countBits(n):
return n.bit_length()
"""
Modulus
"""
def modulus(n):
if type(n)==int :
return n % 2
else:
return -1
#def modulus(n):
# if int(n) == n:
# return n % 2
# else:
# return -1
#def modulus(n):
# if isinstance(n,int) :
# return ... |
import re
import urllib.request
from urllib.request import Request,urlopen
correct="Y"
for i in range(0,20):
try:
word=input("Enter your Word:")
url="http://dictionary.reference.com/browse/"+word
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
data=urlopen(req).read()... |
'''
copy:只复制深层对象的引用
deepcopy:复制深层对象本身
'''
import copy
a = [1,2,3,4,['a','b']]
c = copy.copy(a) # 浅拷贝
d = copy.deepcopy(a) # 深拷贝
print(c)
print(d)
a.append(5)
print(a)
print(c)
print(d)
a[4][0] = 'x'
print('-------------')
print(a)
print(c)
print(d)
|
'''
线程锁:目的是将一段代码锁住,一旦获得锁权限,除非释放线程锁,否则其他任何代码都无法获得锁权限
为什么需要线程锁
由于多线程同时在完成特定的操作时,由于并不是原子操作,所以在完成操作的过程中可能会被打断,去做其他的操作。
可能会产生脏数据
例如,一个线程读取变量n【初始值是0】,然后n++,最后输出n
当访问n++后,被打断,由另外的线程做同样的工作,这时n被加了2次,所以n最后等于2,而不是1
'''
from atexit import register
from threading import Thread,Lock,currentThread
from time import sleep,ctim... |
# 第一题:检测字符串是否为数字
s1 = '12345'
print('12345是数字:',s1.isdigit())
print(int(s1))
s2 = '12345a'
print('12345a是数字:',s2.isdigit())
print('12345a是字母数字混合形式:',s2.isalnum()) #isalnum
s3 = '12_345a'
print('12_345a是字母数字混合形式:',s3.isalnum())
print(" ".isspace())
print("12.45".isdecimal()) # 检测字符串中是否为整数
print("abc3d".isalpha(... |
'''
2,3,5
6
14:不是丑数
下一个丑数必定是数组中的某一个丑数A * 2、B * 3、C*5中最小的值
M2, 之前的丑数*2都小于当前最大的丑数
之后的丑数*2都大于当前最大的丑数
M3、M5
'''
def getUglyNumber(index):
if index < 1:
return 0
res = [1]
t2 = t3 = t5 = 0
nextdex = 1
while nextdex < index:
minNum = min(res[t2] * 2, res[t3] * 3, res[t5] * 5)... |
from menu import MENU
from menu import resources
Water = resources["water"]
Milk = resources["milk"]
Coffee = resources["coffee"]
Income = 0
while 1 > 0:
choice = input("What would you like? espresso/latte/cappuccino) : ")
def coin_check():
print("Please Insert Coins")
quarters = int(input("... |
#The Resteraunt Tipper Program
#It prompts the user for the bill total, and then asks for a percentage for the
#bill total.
#Credits to Olivia and Lerkling Chang.
#I intend to add a user's input on how good the resteraunt was, and then tell
#the user how much percentage they should pay. Give credit to Da Yi when I... |
import sqlite3
"""This is where the tables in the database are made in the case that they are not yet made."""
conn = sqlite3.connect("UPDB.db")
cursor = conn.cursor()
"""Table for the users of JacBank"""
cursor.execute('''
CREATE TABLE IF NOT EXISTS user(
userID INTEGER PRIMARY KEY,
username VARCHAR(20... |
n = int(input('digite o tamanho da sequencia numerica: '))
i = 0
cneg = 0
cnulo = 0
cpos = 0
while i < n:
i += 1
num = int(input('digite um numero: '))
if num > 0:
cpos += 1
elif num == 0:
cnulo += 1
else:
cneg += 1
print(f'{cpos} positivo(s) \n {cnulo} nulo(s) \n {cneg} nega... |
#!/usr/bin/env python
n=int(input("Please Enter The Number:"))
for i in range(1,n//2+1):
print("* "*i)
print("")
for i in range(n//2+1,0,-1):
print("* "*i)
print(" ")
|
class Car:
""" Just simple car abstraction """
def __init__(self, model, maker, release_data):
self.release_data = release_data
self.maker = maker
self.model = model
self.odometer = 0
def car_info(self):
print(f'The car mode is {self.model} was build by {self.maker... |
from unitTest.Survey import Survey_simple
survey = Survey_simple("What is your favourite language? : ")
survey.get_question()
while True:
response = input("If you don't want to answer, press 'q'")
if response != 'q':
survey.set_response(response)
else:
break
survey.show_results()
|
def LCS(first_word, second_word):
matrix = [["" for x in range(len(second_word))] for x in range(len(first_word))]
for i in range(len(first_word)):
for j in range(len(second_word)):
if first_word[i] == second_word[j]:
if i == 0 or j == 0:
matrix[i][j] = fi... |
a, b = map(int,input().split())
result = a * b
if result % 2 == 0:
print("Even")
else:
print("Odd")
|
"""
-------------------------------------------------------
matrix_functions
A library of functions to help with the matrix class.
These are functions that wouldn't really be considered
to be matrix operations but are used in carrying out
matrix operations (helper functions so to speak.)
-------------------------------... |
# by M. Ammar Hanif
from fractions import Fraction as fraction
# harus di revisi lagi, karena masih dirty code
# revisi:
# ----- variabel ngasal
# ----- semua belum menggunakan formatted string
# ----- terakhir, melakukan tes ulang
def menu():
start()
choice = input(" Selamat Datang \n Kalkulator Transformasi ... |
class Student:
def get_age(self):
return self._age
def set_age(self, value):
if value >= 0 and value <= 88:
self._age = value
else:
raise ValueError('年龄必须在0到88之间')
class Student1:
@property
def age(self):
return self._age
@age.setter # 当前属... |
"""
找出满足a+b+c=1000,并且a^2+b^2=c^2的所有组合
方法一:
使用枚举法
"""
import time
start_time = time.time()
for a in range(0, 1001):
for b in range(0, 1001):
for c in range(0, 1001):
if a + b + c == 1000 and a ** 2 + b ** 2 == c ** 2:
print(f'组合{a},{b},{c}满足条件')
print(f'程序结束时间为{time.time() -... |
import threading
import time, os
class MyThreading(threading.Thread):
def run(self):
for i in range(3):
print(f'线程名字{self.name},输出:{i}')
time.sleep(1)
if __name__ == '__main__':
start = time.time()
print(f'主线程开始时间{start}')
s = 'abcdef'
thread_list = []
for i i... |
# 队列实现 链表
class Node:
def __init__(self, data, _next=None):
self.data = data
self.next = _next
class Queue:
def __init__(self, size):
self.head = None # 队列头部
self.rear = None # 队列尾部
self._length = 0 # 队列长度
self.size = size # 队列最大长度
def is_empty(self):
... |
from enum import Enum
# 枚举:一个名字对应一个值 类似于字典
# Month是抬头,可以省略
Month = Enum('Month', ('一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'))
# 拿到枚举里的所有数据
print(Month.__members__) # 枚举中的值从1开始,不会重复
# 通过名字获取值
print(Month['二'].value)
# 通过值获取名字
print(Month(2).name)
# # 自定义一个颜色枚举类
class Color(Enum):
"""
不允... |
def odd_num():
n = 1
while True:
n += 2
yield n
g1 = odd_num()
def my_filter(n):
return lambda x: x % n > 0
def tt():
yield 2
g = odd_num()
while True:
y = next(g)
g = filter(my_filter(y), g)
# g = filter(lambda x :x % y > 0 ,g)
yield y
for... |
# 定义一个元类,用来将属性名全部转为大写
def upper_attr(class_name, class_bases, class_attrs):
new_attrs = {}
for name, value in class_attrs.items():
if not name.startswith('__'): # 判断是否是私有属性
new_attrs[name.upper()] = value
return type(class_name, class_bases, new_attrs)
class Person(object, metaclass=up... |
"""
@Author:hu
@Time:2021/9/4 14:55
@File:队列通信.py
@Software: PyCharm
"""
import threading
import time
from queue import Queue
class Product(threading.Thread):
"""
创建生产者
"""
def __init__(self, q):
"""
初始化实例属性
:param q: 队列
"""
super().__init__()
self.q =... |
# 第一种方式
# from Python高级编程.面向对象进阶.元类.元类 import Person
# 引入模块之后,动态创建了一个Person类 本质上python解释器自动调用了type函数创建了一个类
# def say(name):
# print(f'{name}在吃饭')
# # 第二种方式
# # 使用type()函数创建一个类 参数一:类名,参数二:父类 参数三:类中的方法或者属性
# Person = type('Person', (object,), dict(say=say))
# 第三种方式 使用metaClass创建一个元类
class PersonMetaClass(type... |
def bubblesort(nums):
for i in range(len(nums)-1):
flag = False # 用来记录是否进行了数组的交换
for idx in range(0, len(nums)-1-i):
if nums[idx] > nums[idx+1]:
nums[idx], nums[idx+1] = nums[idx+1], nums[idx]
flag = True # 如果执行了,则代表数组进行了交换
print(f'第{i+1}趟排序',... |
"""
@Author:hu
@Time:2021/9/6 13:37
@File:浅拷贝.py
@Software: PyCharm
"""
import copy
# # a = [1, 2, 3, 4, 5, [9, 0]]
# # b = copy.copy(a)
# # print('外层元素id')
# # print(id(a))
# # print(id(b))
# # #
# # # print(a)
# # # print(b)
# # a[5][0] = 10
# # # print(a)
# # # print(b)
# # print('内部元素的id')
# # print(id(a[1]))
# #... |
# 定义一个函数,计算阶乘
def test1(num):
if num == 1:
return 1
else:
return num * test1(num - 1)
# test2是高阶函数 参数是有一个是函数
def tests2(list1, func):
new_list = []
for i in list1:
new_list.append(func(i))
return new_list
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(tests2(list1, test1))
|
"""
This project demonstrates NESTED LOOPS (i.e., loops within loops)
in the context of PRINTING on the CONSOLE.
Authors: David Mutchler, Valerie Galluzzi, Mark Hays, Amanda Stouder,
their colleagues and Ben Hawkins.
""" # Done: 1. PUT YOUR NAME IN THE ABOVE LINE.
def main():
""" Calls the other functi... |
""" prints the longest substring of s in which the letters occur in alphabetical order"""
def alphabetical_substrings(string):
""" prints the longest substring of s in which the letters occur in alphabetical order"""
max_substring = string[0]
max_number = 1
for i in range(len(string)):
count = 1... |
def addStrings(num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
number_map = {}
#O(1)
for i in range(0,10):
number_map[str(i)] = i
num_arr_str = [num1, num2]
num_arr_int = []
for num1 in num_arr_str:
num1_int = 0
num1_len = len(num1) ... |
# Anagram problem (Easy)
def anagram(A,B)
"""
Returns an array which maps array A to array B
Time complexity : O(N) + O(N) = O(N)
Space complexity: O(N) since we are creating a
new hash map
:type A: List[int]
:type B: List[int]
:rtype: List[int]
"""
hash_b = {b:k for k,b in enume... |
def countBits(num):
"""
:type num: int
:rtype: List[int]
Time O(N)
Space O(N)
"""
for i in range(0,num + 1):
print(list(bin(i)[2:]).count("1"),bin(i)[2:], i)
# print(2**i)
countBits(50)
|
class Solution:
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
counting_sum = True
new_num = num
my_sum = 0
while counting_sum:
my_sum = 0
for x in str(new_num):
my_sum += int(x)
if (my... |
def searchInsert(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
# binary search
max_val = 0
min_val = len(nums)
print(nums)
mid_point = (max_val + min_val) // 2
if target == nums[mid_point]:
return mid_point
if len(nums) < 2:
i... |
import time
from functools import lru_cache
@lru_cache()
def some_work(n):
time.sleep(n)
return n
if __name__ == '__main__':
take_time = eval(input('Input time you want to delay for:'))
lru_input = eval(input('Enter the value for LRU cach:'))
lru_cache(lru_input)
print('Running function.. ')
... |
# grocery = ['harpic', 'egg', 'rice', 'candy' ]
numbers = [6, 8, 2, 10, 15]
# print(grocery)
# numbers.append(20)
# numbers.sort()
# numbers.reverse()
# numbers.pop()
# numbers.insert(1, 50)
print(numbers)
# Swap tuple variable
tp = (11, 12, 13)
tp1 = (0, 1, 2)
# print(tp, tp1)
tp, tp1 = tp1, tp
print(tp, tp1)
# Swa... |
# ----------------------------------MAP----------------------------------------
numbers = ["1", "2", "3", "4"]
# Converting strings of numbers list into a int using for loop
for i in range(len(numbers)):
numbers[i] = int(numbers[i])
print("Numbers as int: ", list(numbers))
print(type(numbers[2]))
numbers[2] = n... |
# defining a class
class Employee:
no_of_employee = 500 # class variable, can't change thorough instance variables
pass
# Creating objects of employee class
anindo = Employee()
harry = Employee()
# Creating instances variables(variables of objects)
anindo.name = 'Anindo Dey'
anindo.age = 25
anindo.salary = ... |
try:
f = open("anindo.txt")
except Exception as e:
print(e)
else:
print('If except is not running then this will print.')
finally:
# f.close()
print('Anyway! Executing this.')
print('This is an important task.') |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# http://d.hatena.ne.jp/naoya/20090412/btree
# t: min degree
class BTree:
def __init__(self, t=2):
self.t = t
self.root = BTree.Node(t)
self.root.is_leaf = True
def insert(self, k):
r = self.root
if len(r) == 2 * self.t - 1:... |
<<<<<<< HEAD
str=input("")
list1=[]
n=len(str)
b=0
while b<n:
c=str[b]
e=ord(c)
list1.append(e)
b+=1
print(list1)
=======
str=input("")
list1=[]
n=len(str)
b=0
while b<n:
c=str[b]
e=ord(c)
list1.append(e)
b+=1
print(list1)
>>>>>>> c4107b7d195ae20fa506d622edecf008161c987... |
# coding=gbk
__author__ = 'renfei'
number = 30
running = True
while running:
guess = int(input("µ"))
if guess == number:
print("ϲ㣬¶ˣ")
running = False # ѭ
elif guess > number:
print("е̫ˣ")
else:
print("̫Сˣ˲£")
else:
print("ִ while ѭִ while else") ... |
__author__ = 'renfei'
zoo=("daxiang","tiger","shizi")
print(zoo)
for item in zoo:
print(item)
new_zoo = ("bird","tuzi",zoo)
print(new_zoo)
print(new_zoo[2][2])
age=23
name="daiwei"
print("%s is %d years old" % (name,age))
|
# ejemplo de manipulación de 'Strings' con funciones predefinidas
# para un lista completa the funciones 'https://www.w3schools.com/python/python_ref_string.asp'
txt = "hello, I LOVE apples, red apple and green apple"
print(txt)
x = txt.capitalize()
print (x) #prints txt with the first letter capitalized
x... |
# the following list contains the age of people
list=[24, 23, 27, 40, 12, 60, 30]
#now we print any of the ages using the position index
print(list)
print(list[0])
print(list[1])
print(list[2])
print(list[6])
# I can list using a reverse order where -1 is the last one and -2 the second last and so on
print("... |
#this program will sum values until 'n'
sum = 0
i = 0
n = int(input("entra el valor the n"))
while i <= n:
print("i va en =", i)
sum += i
print("la sumatoria va en:",sum)
i += 1
print("la suma total es =",sum)
|
# global variables are available globally
# local variables are available only within a function
message1 = "Global Message"
def myFunction():
print("\nInside the function")
print(message1)
message2 = "Local variable"
print(message2)
myFunction()
print("\nOutside the function")
print(message1)
print(message2)
# ... |
# Dictionary is a collection of related data PAIRS
# for example the username and age of 5 people
# dictionary = {dictionary key : data}
# with the requirement that dictionary keys must be unique (within one dictionary)
# for example this is an error:
# dictionary = {"Peter":38, "John":51, "Peter":13}
userNameAnd... |
# Question 8: Longest Repetition
# Define a procedure, longest_repetition, that takes as input a
# list, and returns the element in the list that has the most
# consecutive repetitions. If there are multiple elements that
# have the same number of longest repetitions, the result should
# be the one that appears first.... |
#You can find the puzzle here: https://adventofcode.com/2020/day/10
import sys
#The file containing every numbers
filename = sys.argv[-1]
# =====================
# PART 1
# =====================
#Count the number of different jolt differences
def count_jolt_differences(adaptaters_list):
jolt_dif_list = [... |
inp = input().split()
nums = []
for elem in inp:
nums.append(int(elem))
nums.sort()
x = int(input("What to search? "))
left = 0
right = len(nums) - 1
result = None
while (left <= right) and (result is None):
shaft = (left + right) // 2
if nums[shaft] == x:
result = shaft
elif nu... |
from math import floor, ceil
from tkinter import *
def bt_click():
Pontuacao = 50
numNF = float(cx.get())
numPF = float(cx1.get())
if numNF > 0:
cNF = 0
while (cNF < numNF):
cNF = cNF + 1
Pontuacao = Pontuacao * 1.02
Pontuacao = floor(... |
# "Stopwatch: The Game"
# Click start, stop, and reset buttons to start, stop, and reset the stopwatch.
# Score one point every time the timer is stopped on .0 seconds.
# Counter tracks total attempts.
import simplegui
# define global variables
a = 0 # minutes
b = 0 # tens of seconds
c = 0 # ones of seconds
d = 0... |
hrs = input("Enter Hours:")
rate = input("Enter Rate:")
try:
hours = float(hrs)
rate=float(rate)
except:
print("Error,please enter numeric input")
quit()
print("hours:",hours,"rate:",rate)
if hours>40:
reg = hours*rate
overtime=(hours-40.0)*(rate*0.5)
pay=reg+overtime
else:
pay = hours*rat... |
# Use words.txt as the file name
fname = input("Enter file name: ")
fh = open(fname)
content = fh.read()
content = content.upper()
print(content)
Use words.txt as the file name
# solution to make the program run in the auto grader use rstrip() or strip()
# fname = input("Enter file name: ")
# fh = open(fname)
# cont... |
fileName = input("Enter File Name:")
fileHandle = open(fileName)
dictionary = dict()
for line in fileHandle:
words = line.split()
if words: # if words != []
for word in words:
# idiom: retrieve/create/update counter
dictionary[word] = dictionary.get(word,0) + 1
# find the 10 t... |
print ("Hello User")
print ("I knew you would come back !)")
print ("This time around, we will be multiplying three numbers")
s = int(input("The first number is:"))
a = int(input("The second number is:"))
d = int(input("The third number is:"))
e = (s*a*d)
print ("The product is:", e)
print ("We can never fail you :) Co... |
s = "137"
a = "yans"
print(int(s), type(int(s)))
# print(int(a), type(int(a)))
s="ssssrrfdf"
print(s.split(",")) |
def sleep_in(weekday, vacation):
"""
This function verifies if you can or cannot sleep taking into account weekday and vacation values.
:param weekday: Any bool value
:type weekday: bool
:param vacation: Any bool value
:type vacation: bool
:return: It returns True if weekday is False or vac... |
"""
Author: Rejohn Cuares
Date: 04/02/2019
Version: 2019-02.01
Use case #1: Play music in my car.
I downloaded my music files (i.e. mp3) and saved to
my thumb driver but they are listed not in order even though the files
are alphabetically arrange. This program tries to rename the mp3 files
and ask you to prefix with ... |
from random import randint
a=[randint(1, 200) for i in range(10)]
print(*a)
n=int(input('Введите N: '))
New=[]
for i in a:
ans=0
temp=i
for k in range(3): #вычисление суммы цифр
ans+=temp%10
temp//=10
if ans==n:
New.append(i) #добавляет число в конец массива, как... |
import numpy as np
import copy
import helpers
import time
import val_iter
import pickle
import random
import sys
def simulate_race(world, policy, badcrash = True, animate = False, start = 'S', goal = 'F', frame_time = 0.5):
"""
Simulate a race from a prescribed policy. Determines average speed (performance) of... |
from re import findall
class FileCount:
def __init__(self, file, string):
self.f = file
self.s = string
def string_count(self):
with open(self.f, encoding='utf-8') as f:
result = len(findall(self.s, ''.join([i for i in f])))
return f'String {self.s} ap... |
# indicadores de passagem
n = int(input("Digite o valor de n: "))
i = 1
cont = 0
while cont < n:
if i % 2 != 0:
print(i)
cont = cont + 1
i = i + 1
|
# encoding: utf-8
print("Entre com uma sequencia que termine com 0: ")
soma = 0
produto = 1
num = 1
while (num != 0):
num = int(input("Entre com um numero: "))
if num != 0:
produto = produto * num
soma = soma + num
print("A soma dos numeros eh: ", soma)
print("O produto dos numeros eh: ", pro... |
# coding: utf-8
segundos= int(input("Entre com o numero de segundos: "))
horas = segundos // 3600
rest = segundos % 3600
minutos = rest // 60
rest = rest % 60
# o restante corresponde aos segundos
print(horas, "graus", minutos, "minutos", rest, "segundos")
|
#*********************************** Python 2 **************************************
def calculabonus( salario, montante):
return salario + ((montante * 15)/100)
nome = raw_input()
salario = float(input())
montante = float(input())
total = calculabonus(salario, montante)
print "TOTAL = R$ {0:.2f}".format(total)
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 24 15:52:09 2019
@author: Izabel Santos
"""
import datetime
#dia = int( input("Entre com o dia: " ))
mes = int( input("Entre com o mes: " ))
tempo = datetime.datetime.now()
anocorrente = tempo.year
contames = 0
for i in range(mes+1):
if ( i % 2 == 1 and i < 8 ) or... |
def usertirapecasplural(npecas):
if npecas == 1:
print("Você tirou uma peça.")
else:
print("Você tirou", npecas ,"peças.")
def restapecasplural(n):
if n == 1:
print( "Agora resta apenas uma peça no tabuleiro.\n" )
else:
print( "Agora restam ", n ,"peças no tabuleiro.\n" ... |
# A version of inversions pair finding algorithm designed on the basis of merge sort algorithm
# Courtesy : Tim Roughgarden (coursera: Algorithm design and analysis 1)
import math
def merge_sort(a, p, r):
if p < r:
q = int(math.floor((p + r) / 2))
merge_sort(a, p, q)
merge_sort(a, q + 1, r)
if q != len(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.