text stringlengths 37 1.41M |
|---|
# EX01: Escreva uma função que recebe dois
#parâmetros (números) e imprime o menor dos dois.
#Se eles forem iguais, imprima que são valores idênticos.
def men(n1, n2):
if n1 == n2:
print('Os valores são idênticos.')
elif n1 < n2:
print(f'O menor valor é {n1}')
else:
print(f... |
#Faça um programa, com uma função que necessite de um argumento.
# A função retorna o valor de caractere ‘P’, se seu argumento for positivo,
# ‘N’, se seu argumento for negativo e ‘0’ se for 0.
def pos_neg(n):
if n > 0:
return 'P'
elif n == 0:
return 0
else:
return 'N'
... |
'''Escreva um programa que determine
todos os números de 4 algarismos que
possam ser separados em dois números
de dois algarismos que somados e elevando-se
a soma ao quadrado obtenha-se o próprio número.
Exemplo: 3025 = 55 e 55**2 é igual á 3025'''
for i in range(1000,10000):
if (i // 100 + i // 100)**2 == ... |
#Elaborar um programa que recebe dois valores
#inteiros e mostra a soma desses valores
n1 = int(input('Digite o primeiro número: '))
n2 = int(input('Digite o segundo número: '))
soma = (n1+n2)
print(f'{n1} + {n2} = {soma}')
|
#Mini Projeto 02 - Calculadora de aumento de aluguel
#Parte 2
#Agora, altere sua calculadora para receber além
#do valor do aluguel, o percentual do reajuste no formato XX%.
valor = float(input('Digite o valor do aluguel: '))
print(f'O valor do aluguel atualmente é R$ {valor:.2f}')
per = float(input('Qual o perce... |
#Faça um programa que tenha uma função chamada contador(),
# que receba três parâmetros: início, fim e passo.
#Seu programa tem que realizar três contagens através da função criada:
#a) de 1 até 10, de 1 em 1
#b) de 10 até 0, de 2 em 2
#c) uma contagem personalizada,
from time import sleep
def contador (inicio, fim, p... |
'''Faça um script que peça ao usuário
o número de matérias da escola,
ou seja, um inteiro positivo. Em seguida, ele
vai digitando o valor de cada nota, de
cada matéria e isso será armazenado numa lista.
Ao final, seu script deverá
fornecer a média geral do aluno.'''
i = int(input('quantas materias tem sua aula: ... |
'''Elaborar um programa para imprimir
os números de 1 até 10
em ordem decrescente.'''
n = list(range(1 , 11))
n = sorted(n, reverse=True)
print(n)
|
#
# @lc app=leetcode.cn id=208 lang=python3
#
# [208] 实现 Trie (前缀树)
#
# https://leetcode-cn.com/problems/implement-trie-prefix-tree/description/
#
# algorithms
# Medium (67.16%)
# Likes: 334
# Dislikes: 0
# Total Accepted: 42.6K
# Total Submissions: 63K
# Testcase Example: '["Trie","insert","search","search","st... |
n=int(input())
a=[]
x=input().split(' ')
for i in range (0,n):
a.append(int(x[i]))
for i in range (0, len(a), 2):
print(a[i],end=" ")
|
def alarm_clock(days, vacation):
if vacation:
if days==0 or days==6:
return "off"
return "10:00"
else:
if days==0 or days==6:
return "10:00"
return "7:00" |
def count_hi(str):
c = 0
for i in range(len(str) - 1):
if str[i:i + 2] == "hi":
c += 1
return c |
def make_chocolate(small, big, goal):
maxBig = goal/5
if maxBig <= big:
goal -= maxBig*5
else:
goal -= big*5
if goal <= small:
return goal
return -1 |
a=int(input())
b=int(input())
if (a!=1 and b!=1 or a==1 and b==1): print("YES")
else: print("NO") |
a=int(input())
b=int(input())
c=int(input())
d=int(input())
for i in range(a,b+1):
if i%d==c : print(i, end=" ")
else: print(" ") |
import requests
from bs4 import BeautifulSoup
# This program finds the pizza for the week from the cheeseboard website
url = 'http://cheeseboardcollective.coop/pizza/'
response = requests.get(url)
html = response.content
soup = BeautifulSoup(html, "html.parser")
# print soup.prettify()
pizzas = soup.find("div", cl... |
#three dict must refer to all nodes
infinit = float("inf")
graph = {}
graph["start"] = {}
graph["start"]["a"] = 5
graph["start"]["b"] = 2
graph["a"] = {}
graph["a"]["c"] = 4
graph["a"]["d"] = 2
graph["b"] = {}
graph["b"]["a"] = 8
graph["b"]["d"] = 7
graph["c"] = {}
graph["c"]["end"] = 3
graph["c"]["d"] = 6
graph["... |
ar = [1,2,4,5]
for a in ar:
print(a)
msg = "help342"
print(msg.capitalize())
class A(object):
def __init__(self,a):
self.a = a
def fr(self):
print(self.a)
|
"""Exercise : how many
# write a procedure, called how_many, which returns the
#sum of the number of values associated with a dictionary.
"""
def how_many(a_dict):
'''
:param a_dict: A dictionary, where all the values are lists.
:returns: int, how many values are in the dictionary.
'''
sum_a = 0
... |
"""# Functions - Assignment-3 - Using Bisection Search to Make the Program Faster
# You'll notice that in Problem 2, your monthly payment had to be a multiple
# of $10. Why did we make it that way? You can try running
# your code locally so that the payment can be any dollar and cent amount
# (in other words, the mont... |
num_val = int(input())
guess = num_val/2.0
epsilon = 0.01
while (guess*guess-num_val) >= epsilon and guess <= num_val:
guess = guess-(((guess**2)-num_val)/(2*guess))
print(guess)
|
num_a = int(input())
if num_a > 0:
if num_a % 3 == 0:
print("Fizz")
elif num_a % 5 == 0:
print("Buzz")
if num_a % 3 == 0 and num_a % 5 ==0:
print("Fizz")
print("Buzz")
else:
print("not a multiple of 3 and 5")
|
""" Longest substring in alphabetical order """
string = "abcdbc"
s = 0
count = 0
count1 = 0
for i in range(len(string) - 1):# comparing the indices
if string[i] <= string[i+1]:# comparing the characters in the indices
count += 1
if count > count1:
count1 = count
s = i + 1
... |
# Meu primeiro programa
# Ruan Felipe Bodnar <RuanFelipeBodnar@outlook.com
from random import randint # Importa a função de gerar números aleatórios
print("Jogo dos dados:")
dado1 = randint(1, 6) # gera um número entre 1 e 6 aleatóriamente
print("Dado 1: ", dado1)
dado2 = randint(1, 6) # gera um número entre 1 e... |
def max_num(num1, num2, num3):
if(num1>num2 and num1>num3):
print('num1 is greatest')
return num1
elif (num2>num1 and num2>num3):
print('num2 is greatest')
return num2
else:
print('num3 is greatest')
return num3
print(max_num(3,5,1)) |
class Teman:
JUMLAH = 0
def __init__(self, nama, sex):
self.nama = nama
self.sex = sex
self.alamat = ''
Teman.JUMLAH = Teman.JUMLAH + 1
def __str__(self):
return ('Nama = %s, sex=%s, alamat=%s' % (self.nama, self.sex, self.alamat))
def berbicara(self):
... |
"""
去除英文停用词
"""
import nltk
emma = nltk.corpus.gutenberg.words('austen-emma.txt')
stopwords = nltk.corpus.stopwords.words('english')
print(stopwords)
emma = [w.lower() for w in emma]
emma_without_stopwords = [w for w in emma if w not in stopwords]
print(emma_without_stopwords)
|
# print('hello world')
# name = 'Tom'
# age = 50
# is_male = False
# phrase = 'nicky variable'
# print(phrase.replace('nicky', 'new'))
# print(phrase.index('var'))
# print(phrase.upper())
# print(phrase.lower().islower())
# print(3 * (4+5))
# print(10 % 3)
# my_num = 5
# my_num_as_str = str(my_num)
# print(my_num_as... |
import operator
import sys
import Pmf
entered = raw_input("Enter a sequence of integers you want to find the mode of (comma-seperated): ")
sequence = entered.split(", ")
hist = Pmf.MakeHistFromList(sequence)
histdict = hist.d
print histdict
def Mode(hist):
mode = None
top_freq = 0
for k, v in hist.iteritems()... |
"""
Light demo
"""
import arcade
from arcade.experimental.lights import Light, LightLayer
SCREEN_WIDTH = 1024
SCREEN_HEIGHT = 768
SCREEN_TITLE = "Lighting Demo"
VIEWPORT_MARGIN = 200
MOVEMENT_SPEED = 5
class MyGame(arcade.Window):
""" Main Game Window """
def __init__(self, width, height, title):
"""... |
"""
Array Backed Grid Shown By Sprites
Show how to use a two-dimensional list/array to back the display of a
grid on-screen.
This version syncs the grid to the sprite list in one go using resync_grid_with_sprites.
This is faster than rebuilding a shape list every time the grid changes,
but we are still inspecting eve... |
"""
Emitter - Invisible object that determines when Particles are emitted, actually emits them, and manages them
over their lifetime
"""
from __future__ import annotations
import arcade
from .particle import Particle
from typing import Optional, Callable, cast
from arcade.math import _Vec2
from arcade.types import Poi... |
"""
This example is a proof-of-concept for a UIScrollArea.
You can currently scroll through the UIScrollArea in the following ways:
* scrolling the mouse wheel
* dragging with middle mouse button
It currently needs the following improvements:
* A better API, including scroll direction control
* UIScrollBars
If arc... |
"""
Parallax scrolling layers move slower the "farther" away they are.
Use the right and left arrow keys to move the car.
Arcade's ParallaxGroup allows you to implement this technique quickly
to create more satisfying backgrounds to your games. The example below
demonstrates how to fake an endless world by adjusting ... |
"""
This module provides a Scene class which acts as a sprite list manager.
It allows you to do the following:
* Group sprite lists into a larger object, using them like layers
* Draw & update the contained sprite lists
* Add sprites by name
* Load from tiled map objects
* Control sprite list draw order within the gr... |
"""
Sprite Rotation Around a Point, With A Tank
Games often include elements that rotate toward targets. Common
examples include gun turrets on vehicles and towers. In 2D games,
these rotating parts are usually implemented as sprites that move
relative to whatever they're attached to.
There's a catch to this: you hav... |
"""
Creating sidebar-like layouts with UIBoxLayout
This example creates left, right, top, and bottom bars by combining the following:
* Placing box layouts inside other box layouts (see the box_layouts example)
* Size hints (see the size_hints example)
To turn this into a real UI, you can replace the UIDummy widget... |
"""
Array Backed Grid
Show how to use a two-dimensional list/array to back the display of a
grid on-screen. We can click each cell in the window to toggle the color
or each individual cell.
This is not the most efficient way to maintain an updated grid
simply because we have to rebuild the shape list from scratch
eve... |
"""
Example of Pymunk Physics Engine Platformer
"""
import math
from typing import Optional
import arcade
SCREEN_TITLE = "PyMunk Platformer"
# How big are our image tiles?
SPRITE_IMAGE_SIZE = 128
# Scale sprites up or down
SPRITE_SCALING_PLAYER = 0.5
SPRITE_SCALING_TILES = 0.5
# Scaled sprite size for tiles
SPRITE_... |
"""
CHIP-8 is an interpreted minimalist programming language that was designed by
Joseph Weisbecker in the 1970s for use on the RCA COSMAC VIP computer.
This example renders a 64 x 32 pixel display. The pixel format is using
bits to represent what pixel is enabled/disabled so the byte size of
the buffer is 8 x 4 = 32 ... |
"""
Show how to use lights.
.. note:: This uses features from the upcoming version 2.4. The API for these
functions may still change. To use, you will need to install one of the
pre-release packages, or install via GitHub.
Artwork from http://kenney.nl
"""
import arcade
from arcade.experimental.l... |
"""
Sprite Bullets
Simple program to show basic sprite usage.
Artwork from https://kenney.nl
If Python and Arcade are installed, this example can be run from the command line with:
python -m arcade.examples.sprite_bullets_aimed
"""
from __future__ import annotations
import random
import arcade
import math
SPRITE_... |
"""
Shapes buffered in ShapeElementList
Show how to use a ShapeElementList to display multiple shapes on-screen.
If Python and Arcade are installed, this example can be run from the command line with:
python -m arcade.examples.shapes_buffered
"""
from __future__ import annotations
import random
import arcade
from ar... |
"""
Defender Clone.
This example shows how to:
1. Create a mini-map
2. Create a 'bloom' or 'glow' effect.
If Python and Arcade are installed, this example can be run from the command line with:
python -m arcade.examples.defender
"""
from __future__ import annotations
import arcade
import os
import random
# --- Blo... |
# no need to use (Object) syntax - it usually just bogs down the readability.
# if it doesn't inherit from anything, make that clear by omitting the (...) bit
class Website:
def __init__(self, entry_url):
self.url = entry_url
self.pages = []
#create a function that gets URL (def URL)
#crea... |
from itertools import*
class Solution:
def countAndSay(f,n,s="1"):return s if n<2else f.countAndSay(n-1,"".join(str(len(list(v)))+d for d,v in groupby(s)))
|
def remainder_one(elements):
out = []
counter = 0
for element in elements:
if counter % 5 != 1:
out.append(element)
counter += 1
return out
#solution
def remainder_one(elements):
return [num[1] for num in enumerate(elements) if num[0] % 5 != 1 ]
# Takes a list of tuples e... |
def reverse(num):
result = int(str(num)[::-1]) if num > 0 else int('-' + str(num)[::-1].replace('-',''))
return result if -2147483648 <= result <= 2147483647 else 0
|
#!/usr/bin/python3
"""
The 3-python_route module
Starts a Flask web application
"""
from flask import Flask, escape, request
app = Flask(__name__)
@app.route('/', strict_slashes=False)
def hello():
"""
Return: a string
"""
return 'Hello HBNB!'
@app.route('/hbnb', strict_slashes=False)
def hello_... |
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
self.diff = {}
def insert(self, key):
node = Node(key)
if self.root == None:
self.root = node
else :
self.insertNode(self... |
# -*- coding: UTF-8 -*-
import os,random #biblioteca de comandos do SO e randômica
os.system("clear") #limpa tela
var1 = random.randint(0,100) #atribui número randômico na var1
n = 0 #zera contador
print("Adivinhe o número entre 0 e 100:")
var2 = 1000 #força um número diferente à var2
while var2 != var1: #enlace... |
import turtle
import time
t = turtle.Pen()
t.color("green")
t.speed(10)
#turtle.speed(speed) 画笔绘制的速度范围[0,10]整数
def 上() :
t.heading()
t.left(90)
t.forward(50)
def 下() :
t.heading()
t.right(90)
t.forward(50)
def 小畫家():
while(True):
key = input("")
if ord(key) == 119:
... |
# 2つの整数の割り算関数div ただし小数点第一位までにすること
def div(x, y):
return round(x / y, 1)
assert 5.0 == div(10, 2)
assert 3.3 == div(10, 3)
|
#!/usr/bin/env python
# _*_ coding: utf-8 _*_
#luz maria calderon aguilera
#2-b
import matplotlib.pyplot as plt
import numpy as np
import math
x=np.linspace(0,2,100)
f=x*np.e**-3*x
g=np.e**-3*x*(1-3*x)
plt.plot(x,f, linewidth=3,color='r',label='linea1')
plt.plot(x,g, linewidth=3,color='b',label='linea2')
pl... |
start_symbol = int(input())
stop_symbol = int(input())
for i in range(start_symbol, stop_symbol+1):
print(f'{chr(i)} ', end="")
|
electron_count = int(input())
def level_count_fn(number_of_electrons):
level_num = 0
electron_levels = []
while number_of_electrons > 0:
current_level_max_count = 2 * (level_num + 1) ** 2
if current_level_max_count <= number_of_electrons:
electron_levels.append(current... |
import re
sequence = input()
sub_domain = r"(www.\b)"
domain = r"([A-Za-z\d\-]+)"
domain_extension = r"((\b.[a-z]+)+)"
pattern = rf"({sub_domain}{domain}{domain_extension})"
while True:
if not sequence:
break
matches = re.search(pattern, sequence)
if matches is not None:
print(mat... |
nums = list(map(int, input().split(" ")))
invert_nums = []
for num in nums:
if int(num) == 0:
num = 0
if int(num) > 0:
num = - num
else:
num = abs(num)
invert_nums.append(num)
print(invert_nums)
|
factor = int(input())
count = int(input())
multiple_list = []
for i in range(1, count+1):
multiple_list.append(i * factor)
print(multiple_list) |
simple_text = input()
simple_text = "".join(simple_text)
ciphered_text = []
for symbol in simple_text:
symbol = ord(symbol) + 3
ciphered_text.append(chr(symbol))
print("".join(ciphered_text))
|
employee_happiness = [int(happiness) for happiness in input().split(" ")]
happiness_factor = int(input())
greater_employee_happiness = list(map(lambda h: h*happiness_factor, employee_happiness))
average_happiness = sum(greater_employee_happiness) / len(greater_employee_happiness)
|
n = int(input())
capacity = 0
for i in range(0, n):
new_liters = int(input())
if capacity + new_liters > 255:
print("Insufficient capacity!")
else:
capacity += new_liters
print(capacity) |
def smallest_number(a, b, c):
smallest_num = None
if c > a < b:
smallest_num = a
if a > c < b:
smallest_num = c
if a > b < c:
smallest_num = b
return smallest_num
first_num = int(input())
second_num = int(input())
third_num = int(input())
print(smallest_numb... |
notes = []
while True:
command = input()
if command == "End":
break
tokens = command.split("-")
importance = int(tokens[0])
note = tokens[1]
notes.append((importance, note))
def sort_fn(element):
return element[0]
sorted_tasks = sorted(notes, key=sort_fn)
print(... |
import random
from art import logo
# METHODS
def choose_number_of_attempts():
if input("Choose difficulty (type easy or hard): ").lower() == "easy":
return 10
else:
return 5
def will_play_again():
if input("Play again? (y/n) ").lower() == "y":
return True
else:
return... |
import pyzipper
import os
def delete_from_zip(zip_filename, files_to_delete, password=None):
# Create a temporary ZIP file name
temp_zip = zip_filename + '.temp'
with pyzipper.AESZipFile(zip_filename, 'r') as zip_read:
# Check if the ZIP is password protected
if password:
z... |
#non repeating charachters
#In this task you should implement an algorithm which finds the first letter in a character
#sequence which is not repeating. This algorithmic problem is a typical problem which
#can be solved in multiple ways. Some are easy to understand and some are complex
#but very efficient. Maybe you... |
import palindromes
import csv
if __name__ == "__main__":
output = [("decimal", "smallest base in which the number is a palindrome")]
for n in range(1, 1001):
output.append((n, palindromes.find_lowest_palindrome_base(n)))
with open('output.csv', 'w') as file_out:
csv_out = csv.writer(file_ou... |
ans=1
change=input()
size_input=len(change)
for i in range(size_input):
if change[i]=='A':
if ans==1:
ans=2
elif ans==2:
ans=1
elif change[i]=='B':
if ans==2:
ans=3
elif ans==3:
ans=2
elif change[i]=='C':
if ans==1:
... |
import sys
class SquareMatrix():
def __init__(self, rows):
self.matrix = self.create_matrix(rows)
def create_matrix(self, rows):
matrix = []
for i in range(rows):
matrix.append([])
for j in range(rows):
matrix[i].append(0)
r... |
def main():
#get three names
print("enter three numbers")
name1 = input(" #1: ")
name2 = input(" #2: ")
name3 = input(" #3: ")
#open file named friends.txt.
myfile = open("numbers.txt", 'w')
#write names to the file
myfile.write(name1 + '\n')
myfile.write(name2 + ... |
# Write a recursive function that accepts an integer argument, n.
# The function should display
# n lines of asterisks on the screen, with the first line showing 1 asterisk,
# the second line
# showing 2 asterisks, up to the nth line which shows n asterisks.
#12.3 Recursive Lines
m = 3
n = 6
def ackerma... |
print("starting program")
file = open('euler67text.txt')
lines = file.readlines()
lists = []
for l in lines:
lists.append(l.split(' '))
for l in range(0, len(lists)):
for s in range(0, len(lists[l] )):
lists[l][s] = int(lists[l][s][0:2])
for i in range(len(lists) - 1, 0, -1):
for j... |
from tkinter import *
import random
root=Tk()
root.title("Password Generator")
root.geometry("400x400")
label=Label(root)
array_3d=[[[1,2,3,4,5,6],["Heads","Tails"],["A","B","C","D","E","F","G","H"]]]
print(array_3d[0][2][3])
def new_password():
random_number_1=random.randint(0, 5)
random_numb... |
# coding: utf-8
# In[4]:
class Animal():
voice = ''
def __init__(self, name, weight):
self.name = name
self.weight = weight #Кг
def to_feed(self, feed): #Корм в килограммах
self.weight += feed
def say_something(self):
print(self.voice)
... |
"""
Lista 02. Questao 01.
Metodo de Newton-Raphson para encontrar raizes aproximadas de equacoes com uma aproximacao inicial e uma tolerancia para f(x).
"""
import math
# quando flag ativa, exibe informacoes durante o processo
LOG = True
'''
f(x) = x^2 + log(x)
'''
def f1(x):
return x ** 2 + math.log(x)
'''... |
# coding: utf-8
# # Anna KaRNNa
#
# In this notebook, I'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book.
#
# This network is based off of Andrej Karpathy's [post on RNNs](http://karpathy.github.io/2015/05/21... |
# prints all nodes in a linked list
from linked_list.UnorderedList import UnorderedList
my_list = UnorderedList()
# my_list.add(1)
# my_list.add(3)
# my_list.add(4)
my_list.add(5)
my_list.add(4)
my_list.add(7)
my_list.add(4)
my_list.add(10)
my_list.add(20)
# my_list.remove_duplicates()
# print
my_list.print()
prin... |
import unittest
from Calculator.Calculator import Calculator
class MyTestCase(unittest.TestCase):
def setUp(self):
self.calculator = Calculator()
def test_instantiate_calculator(self):
self.assertIsInstance(self.calculator, Calculator)
def test_calculator_return_sum(self):... |
#d
def arm(n1):
d=0
m=0
while n1>0:
d=n1%10
m+=d*d*d
n1=n1//10
return m
n=int(input())
c=arm(n)
if c==n:
print("yes")
else:
print("no")
|
def CaesarEncrypt(plaintext, key):
ans = ""
for letter in plaintext:
if letter >= 'a' and letter <= 'z':
ans += chr((ord(letter) - ord('a') + key) % 26 + ord('a'))
elif letter >= 'A' and letter <= 'Z':
ans += chr((ord(letter) - ord('A') + key) % 26 + ord('A'))
... |
def getName():
name = input("What is your name? ")
return name
def getActivity():
activity = input("wanna go outside (ew) or play a game? ")
while activity != "game" and activity != "outside":
print("please input either 'game' or 'outside' :)")
activity = input("wanna go outside (ew) or... |
food = input("What's your favorite food? ")
print("Hmm, " + food + " sounds pretty good!") |
#Installing Django to our directory
# install django (pip install Django)
#to make new project (django-admin startproject project_name)
#to start the server (python manage.py runserver) manage.py helps us using command in our django app, click on the ip adress to check if weverything works successfully
#to ... |
from datetime import datetime
from pygame import mixer
from time import time
print(" Welcome to the Initiative of making you a Healthy Programmer")
print("\nYou'll be reminded to:\nDrink Water after every hour\nRelax your Eyes after 30 minutes\nDo Physical activity every 45 minutes")
def music(file,... |
"""
This module lets you practice DEBUGGING when RUN-TIME EXCEPTIONS occur.
Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher,
Valerie Galluzzi, Mark Hays, Amanda Stouder, Aaron Wilkin,
their colleagues, and Ben Hawkins.
""" # Done: 1. PUT YOUR NAME IN THE ABOVE LINE.
import rosegra... |
"""
fix the below code to return:
1
2
4
5
6
"""
i = 1
while i <= 6:
if i != 3:
print(i)
i += 1 |
'''x=0
while (x<6):
print(x)
x=x+1
'''
sum=0
x=int(input("num:"))
while (x!=0):
sum=sum+x
print(sum)
x=int(input("num:"))
print(sum)
|
a=[0,1,2,3,4,5]
for x in a:
if x==2:
continue
print(x)
print("--X+9",x+9)
|
import calendar
import datetime
from collections import deque
import itertools
class BaseCalendarMixin:
"""カレンダー関連のMixinの、基底クラス"""
first_weekday = 6
# これは日曜日からかくことを想定している
week_names = ['月', '火', '水', '木', '金', '土', '日']
def setup_calendar(self):
"""内部カレンダーの設定処理
calendar.Calendarク... |
# in keyword in sets and for loop
# we use set to remove duplicates and also to perform set operations
s = {'a', 'b', 'c'}
# # in keyword to check if item is present or not in set
# if 'a' in s:
# print("present")
# else:
# print("not present")
# # for loop
# for item in s:
# print(item)
s1 = {1,2,3,4}... |
# to find folder inside folder and file inside folder
import os
import shutil
# os.chdir(r'D:\COMPLETE PYTHON-3 COURSE\Chapter-20-OS_MODULE')
# print(os.listdir())
#fileiter = os.walk(r'D:\COMPLETE PYTHON-3 COURSE\Chapter-20-OS_MODULE')
#for current_path, folder_names, file_names, in fileiter:
# print(f'Current path... |
# something more about tuples, list , str
nums_tup = tuple(range(1,11))
#print(nums_tup) # output = "(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)"
#print(type(nums_tup))
nums_list = list((1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
#print(nums_list)
#print(type(nums_list))
# nums_str = str((1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
# print(nums_str)
... |
# ***************Summary of Chapter One*************
# print function
print("Hello World")
print("Hello 'hello' world")
print("I'm an Student")
print('Hello "Hello" world')
#print('hello 'hello' world') #can't use both single or both double quote
# escape sequence
print("line A \tline B")
print("line B")
print("Thi... |
# class method as a constructor
class Person:
count_instance = 0 # class variable / class attribute
def __init__(self,first_name, last_name, age):
Person.count_instance += 1
self.first_name = first_name
self.last_name = last_name
self.age = age
@classmethod
def from_str... |
# last exercise
# function
# [1,2,3 [1,2], [3,4]], input
# 2
# type()
lst = [1,2,3, [1,2],[1,2], [3,4]]
def count_list(l):
count = 0
for i in l:
if type(i) == list:
count += 1
return count
print(count_list(lst)) |
# some more methods to add data in our list
# append method
# insert method
# how to join(concatenate) two list
# extend method
# difference b/w append and extend method
# append method # it adds in the last position of list
fruits = ['mango', 'orange']
fruits.append('apple')
print(fruits)
# insert method # i... |
# break and continue keyword
# 1 to 10 print
# break statement
print("Break Satatement")
print("Range number 1 to 10, but break before 5")
for i in range(1, 11):
if i == 5:
break
print(i) # it print 1,2,3,4
# continue statement
# print 1 to 10, but not 5
# 1,2,3,4,6,7,8,9,10
print("Continue Satateme... |
# set data type
# unordered(not index wise) collection of unique items
# s = {1,2,3}
# print(s) # only unique values
# print(s[1]) # error
# 1. can store int, float, string in set
# 2. can't store list and dict inside set
# 3. if two values 1 and 1.0 or 3 and 3.0 considers both same
s = {1,1.0,2.3,'string'}
# prin... |
num_1 = int(input("Enter first Number: "))
num_2 = int(input("Enter Second Number: "))
total = num_1 + num_2
print("Total is " + str(total))
number1 = str(4)
number2 = float("44")
number3 = int("33")
print(number2 + +number3) # float
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.