text stringlengths 37 1.41M |
|---|
anterior = int(input("Digite um primeiro valor inicial:"))
decrescente = True
valor = 1
while valor != 0 and decrescente:
valor = int(input("Digite o valor da sequência:"))
if anterior < valor:
decrescente = False
anterior = valor
if decrescente:
print("Decrescente.")
else:
print("Não decr... |
x = int(input("Enter a number: "))
i = 1
while i < x+1:
n = 1
while n <= x:
print( "%4d" % (i * n),end="")
n += 1
print ("")
i += 1
print() |
numbers = ['1', '6', '8', '1', '2', '1', '5', '6']
numb = input("Enter a number? ")
sum= sum(x == numb for x in numbers)
print("{} appears {} in my list".format(numb, sum))
# count = 0
# for n in numbers:
# if n == numb:
# count += 1
# print("{} appears {} in my list".format(numb, count))
|
radius = input(" Radius ?")
r = float(radius)
area = 3.14 * r **2
print( "Area = ", area) |
some_list = ['192.168.1.1', '10.1.1.1', '10.10.20.30', '172.16.31.254']
ip_address_list = some_list
print(ip_address_list)
for ip in ip_address_list:
print("My IP address is")
print(ip)
print("the end")
print(ip_address_list[1])
print("-"*40)
#Enumerate with index plus the value in a tuple
for my_var i... |
# Lamda Functions
# one line disposible functions
def my_func(x):
return x**2
print(my_func(10))
print('-'*40)
# assigned value is variable x, and what is the return value
# Why is it used? Useful to have function that can be passed as an argument. Easy to defice and use in one line
f = lambda x: x**2
print(f(1... |
"""Open the "show_version.txt" file for reading. Use the .read() method to read in the entire file contents to a variable.
Print out the file contents to the screen. Also print out the type of the variable (you should have a string at this point).
Close the file.
Open the file a second time using a Python context ma... |
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import numpy as np
rulenumber = int(input("Enter the number of the rule you will use: "))
#rule 1
if rulenumber == 1:
dA = float(input("Enter value for dA: "))
c = float(input("Enter value for c: "))
def rule1(dA, c):
dQ = abs(c)*dA
retu... |
import pygame
pygame.init()
def click():
if pygame.mouse.get_pressed()==(True, False, False):
return True
def mouse_over():
mx, my = pygame.mouse.get_pos()
if mx > 50 and mx < 100 and my > 50 and my < 100:
return True
else:
return False
#Mouse is hovering over button
... |
"""
根据一定文件夹结构下的图片,生成训练或检验所需的列表文件
Example train.txt:
/path/to/train/image1.png 0
/path/to/train/image2.png 1
/path/to/train/image3.png 2
/path/to/train/image4.png 0
.
.
@author: wgshun
"""
import os
import re
import shutil
def cut(x):
x = x.split('_')
n = ''
for i in x[:-1]:
n += '_' + i
ret... |
from string import ascii_lowercase
text = """
One really nice feature of Python is polymorphism: using the same operation
on different types of objects.
Let's talk about an elegant feature: slicing.
You can use this on a string as well as a list for example
'pybites'[0:2] gives 'py'.
The first value is inclusive and ... |
def function():
if a>b and a>c:
print(a," is max num")
if b>a and b>c:
print(b," is max num")
if c>a and c>b:
print(c," is max num")
a=int(input("enter any num"))
b=int(input("enter any num"))
c=int(input("enter any num"))
function() |
##################################################
## This script generates a report of an exam with section wise marks for all students appeared in exam by taking data from CSV
##################################################
## Author: Pennada S V Naga Sai
## Email: psvnagasai@gmail.com
#######################... |
from typing import List
'''
1. Container With Most Water
Given a non-negative integers a1, a2, ..., an, where each represents a point at
coordinate (i, ai). n vertical lines are draw such that the two endpoints of line
i is at (i,ai) and (i, 0). Find two lines, which together with x-axis forms a
container, such that ... |
from typing import List
from utils import build_tree
from utils.types import Node
'''
590. N-ary Tree Postorder Traversal
Given an n-ary tree, return the postorder traversal of its nodes' values.
Nary-Tree input serialization is represented in their level order traversal, each
group of children is separated by the ... |
import math
from utils import build_list_node
from utils.types import ListNode
'''
21. Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new list. The new list should be
made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4-... |
import math
from typing import Union # noqa
class ListNode:
def __init__(self, x: int) -> None:
self.val = x
self.next: Union[ListNode, None] = None
def __repr__(self) -> str:
values = []
cls: Union[ListNode, None] = self
while cls:
values.append(str(cls.... |
from typing import List
'''
1. Two Sum
Given an array of integers, return indices of the two numbers such that
they add up to a specific target.
You may assume that each input would have exactly one solution, and you
may not use the same element twice.
Examples:
Given nums = [2, 7, 11, 15], target = 9
Be... |
from typing import List
'''
14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of
strings.
If there is no common prefix, return an empty string ''.
Example 1:
Input: ['flower', 'flow', 'flight']
Output: 'fl'
Exmaple 2:
Input: ['dog', 'racecar', 'car']... |
from utils import build_binary_tree
from utils.types import TreeNode
'''
404. Sum of Left Leaves
Find the sum of all left leaves in a given binary tree.
Example:
3
/ \
9 20
/ \
15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively.
Return 24.
'''
EXAMPLES = ... |
from typing import List
from utils import build_binary_tree
from utils.types import TreeNode
'''
437. Path Sum III
You are given a binary tree in which each more contains an integers value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must ... |
r=input()
x=['a','e','i','o','u']
if r in x:
print('vowels')
else:
print('invalid')
|
import random
import pygame
import tkinter as tk
from tkinter import messagebox
from collections import Counter
'''
Drawing in pygame starts in upper left hand corner of object
'''
class Cube(object):
rows = 20
w = 500
def __init__(self, start, dirnx=1, dirny=0,color=(255,0,0)):
self.pos = start
... |
class HashFunction:
def __init__(self, size):
self.list_size = size
self.the_list = []
for i in range(size):
self.the_list.append("-1")
def hash_func_1(self, str_list):
for j in str_list:
index = int(j)
self.the_list[index] = j
def hash_f... |
#Create a program that plays the game "Plinko" with the EV3 robot.
#The robot will 'fall' down a series of white pieces of paper randomly.
#This will be accomplished by creating an array of left and right moves that EV3 can do,
#but the user will select n number of terms to determine which moves are called
#and guess w... |
###Part 1
class Member():
def __init__(self, name):
self.name = name
def intro(self):
print(f'Hi! My name is {self.name}')
class Student(Member):
def __init__(self,name, reason):
Member.__init__(self, name)
self.reason = reason
class Instructor(Member):
def __init__(se... |
def computepay(h,r):
if h>40 :
return 40*10.5+(h-40)*10.5*1.5
else :
return (h)*10.5
#return ((h>40)?40*10.5+(h-40)*10.5*1.5:(h)*10.5)
hrs = input("Enter Hours:")
h=float(hrs)
rate=input("Enter Rate:")
r=float(rate)
p = computepay(h,r)
print("Pay",p)
|
#!/usr/bin/env python3
def cod_virgulas(spam):
""" Imprime todos os itens separados por uma vírgula e um espaço,
com and inserido antes do último item. """
new_spam = []
# inserir ',' aos itens da lista original, excluindo os dois últimos.
for item in spam[:-2]:
new_spam.append(item + ','... |
#!/usr/bin/env python3
# Este é um jogo de adivinhar o número.
import random
# Gera um número aleatório entre 1 e 20.
secretNumber = random.randint(1, 20)
print("I am thinking of a number between 1 and 20.")
# Peça para o jagodor adivinhar 6 vezes.
for guessesTaken in range(1, 7):
print("Take a guess.")
gue... |
# x=lambda a:a+3
# print(x(5))
# y=lambda a,b:a*b
# print(y(3,4))
def multiply(n):
return lambda a:a*n
num1=multiply(6)
print(num1(11))
num2=multiply(7)
print(num2(11))
|
from tkinter import *
root=Tk()
Label(root,text="x direction",bg="red").pack(fill=X)
Label(root,text="y direction",bg="cyan").pack(side=RIGHT,fill=Y)
root.mainloop() |
def squarevalues():
l=list()
for i in range(1,10):
l.append(i**2)
print(l)
squarevalues() |
from tkinter import *
import tkinter.messagebox
root=Tk()
# tkinter.messagebox.showinfo("title","this is information")
# tkinter.messagebox.showwarning("WARNING","This is warning")
# tkinter.messagebox.showerror("ERROR","404 error is found")
msgbox=tkinter.messagebox.askquestion("Main","Do you need to continue?")
if m... |
class student:
def __init__(self,name,mark):
self.name=name
self.mark=mark
def getData(self):
self.name=input("enter your name: ")
self.mark=input("enter your mark: ")
def putData(self):
print(self.name,"\n",self.mark)
obj=student("","")
obj.getData()
obj.putData()
|
# try:
# a=100
# b=0
# print(a//b)
# except:
# print('sorry')
# finally:
# print("its finally")
try:
list=[1,2,3,4,5,6,7]
print(list[3])
except:
print("sorry elements is not found")
finally:
print("its finally") |
from functools import wraps
# ------ basic example of a function decorator ------------
def add_greeting(f):
@wraps(f)
def wrapper(*args, **kwargs):
print("Hello!")
return f(*args, **kwargs)
return wrapper
@add_greeting
def print_name(name):
print(name)
print_name("sandy")
# --... |
# Tyler M Smith
# Section A06
# tsmith328@gatech.edu
# I worked on this assignment alone, using only this semester's course materials.
import math
def celciusToFahrenheit():
c = float(input('Enter temperature in Celcius'))
c1 = c / 5 #F = ((9/5) * C ) + 32
c2 = c1 * 9
c3 = c2 + 32
print('The tempe... |
import httplib2
import string
'''Using a dataset ( the "Adult Data Set") from the UCI Machine-Learning Repository we can predict based on a number of
factors whether someone's income will be greater than $50,000.
The technique:
The approach is to create a 'classifier' - a program that takes a new example record ... |
def distance_from_zero(wok):
if type(wok) == int or type(wok) == float:
return abs(wok)
else:
return "nope"
print(distance_from_zero(-12))
def rental_car_cost(days):
car_cost = 40 * days
# if days > |
grade = float(input("Enter your Grade in %: "))
if grade >= 90:
print("Your grade is A")
else:
if grade >= 80:
print("Your grade is B")
else:
if grade >= 70:
print("Your grade is C")
else:
if grade >= 60:
print("Your grade is D")
... |
try: # start with try when using exception handling.
x = int(input('enter number: '))
except Exception: # not recommended, it's GENERIC error exception. whenever an error occurs it will appear
print('An error occurred')
except ZeroDivisionError:
print('You can\'t div... |
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
"""
initialIntervals = len(intervals)
result = []
for newInterval in intervals:
isNewInterval = True
if... |
""" Нужно запилить класс или несколько классов, в которых нормальным образом
будут храниться точки и их принадлежность и положение на кругах """
import math as m
import networkx as nx
import calculations as calc
import copy as cp
class Point():
def __init__(self, x, y, alpha, circle):
self.xy = cp.deepc... |
#variables
myVar = 5
otherVar = "cancer"
#comment
print(myVar)
print(otherVar)
#Var type
print(type(myVar))
print(type(otherVar))
#string
x = "string"
x = 'string'
#multiple value
one, two, three = "one", "two", "three"
print(one)
print(two)
print(three)
|
import turtle
print 'What is the size of the board: Default size = 40'
harsha=40
harsha=int(raw_input())
class TicToe(object):
def __init__(self):
for k in range(0,harsha*3,harsha):
for j in range(0,harsha*3,harsha):
#a=turtle.pos()
turtle.sety(j)
turt... |
def convert_hex_to_rgb(hex_name):
string = str(hex_name)
rgb = [0,0,0]
rgb[0] = int("0x" + string[0].lower() + string[1].lower(),0)
rgb[1] = int("0x" + string[2].lower() + string[3].lower(),0)
rgb[2] = int("0x" + string[4].lower() + string[5].lower(),0)
return rgb
def elo(eloA, eloB, score_A):
... |
n1 = float(input('Enter the first number: '));
n2 = float(input('Enter the second number: '));
n3 = float(input('Enter the thrid number: '));
if n1 > n2 and n1 > n3 and n2 > n3:
print(f'The first number is the bigger is the third is the smaller.');
elif n2 > n3 and n2 > n1 and n1 > n3:
print('The second number ... |
# Faça um programa que pergunte o preço de três produtos e informe qual produto você deve comprar, sabendo
# que a decisão é sempre pelo mais barato.
n1 = float(input('Enter the price of spaghetti: '));
n2 = float(input('Enter the price of soda: '));
n3 = float(input('Enter the price of banana: '));
if n1 < n2 and n1 <... |
sexo = str(input('Digite "F" para Feminino ou "M" para Masculino.'));
if sexo.lower() == 'f':
print(f'Mulher.');
elif sexo.lower() == 'm':
print(f'Masculino.');
else:
print(f'Sexo inválido.');
|
#!/usr/local/bin/python3
# NAME: NESTOR ALVAREZ
# FILE: shape.py
# DESC: A Shape class from The Quick Python Book (p. 30), set x,y coordinates,
# moves objects, and reports location.
import math
class Shape:
def __init__(self, x, y):
"""Assign x,y coordinates to the object"""
... |
# Cole Rau -- TCSS 142, Section A
# Code logic:
# The program starts with the function "main." The variable "user_napier1" is tested using the
# "character_validation" function. If "user_napier1" is a character, "user_napier1" is passed to the function
# "letters_to_numbers," which translates "user_napier1" (a charact... |
def test_abs1():
assert abs(-42) == 42, "Should be absolute value of a number"
def test_abs2():
assert abs(-42) == -42, "Should be absolute value of a number"
# Команда для запуска с подробным отчетом
# pytest -v stepik_auto_tests_course/S3_lesson3_step8.py
|
nome = input ("digite seu nome:")
print("ola!" ,nome)
perg1 = int(input( "você tem quantos anos?"))
print("olha você tem" , 14, "anos")
if perg1 > 18 :
print("você é de maior!")
else:
print("você não é de maior")
pais= input("você é brasileiro?")
if pais == "sim":
print("você é brasileiro aue legal... |
nihi# -*- coding: utf-8 -*-
"""
Created on Sat Sep 23 22:34:27 2017
@author: Nikhil Bansal
* Objective : Find longest string in incresing alphabetic order
"""
alphabet = "abcdefghijklmnopqrstuvwxyz"
str = input("type : ")
#check and reprompt if user enter empty string
while len(str) <= 0:
print("P... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 3 22:13:45 2018
@author: Nikhil Bansal
Here we are going to create a word counter.
* steps - 1. We are gointn to screap a web page to get words.
"""
import requests
from bs4 import BeautifulSoup
import re
import operator
# This method is going to give... |
# -*- coding: utf-8 -*-
import random
import avengers_helpline
"""
Created on Tue May 8 22:58:43 2018
@author: Nikhil Bansal
* Module - A python file which contain python code
- Generally contains function, which are going to be resued by other python files
* Use - Modularity in programs and r... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 8 22:42:58 2018
@author: Nikhil Bansal
* Dictonary - similar to map
- have key, value pairs
"""
#this will create an empty dict
avengers_ids = dict()
avengers_ids["Iron Man"] = "Tony Stark"
avengers_ids["Spider Man"] = "Peter parker"
avengers... |
import threading
"""
Created on Sun Jun 3 16:05:35 2018
@author: Nikhil Bansal
* Thread - a Sub process that can run independently
* To create thread in python - 1. Import "threading" module.
2. create subclass of "threading.Thread" class and override "run()" method.
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 3 22:10:28 2017
@author: Nikhil Bansal
"""
count = 0
s = input("enter string : ")
i = 0
state = 0
while i < (len(s)):
if s[i] == "b":
if state == 0:
state = 1
if state == 2:
count += 1
state = 1
... |
from abc import ABCMeta, abstractmethod
HE_BETRAYED_ME = 0
BOTH_BETRAYED = 1
BOTH_COOPERATED = 3
I_BETRAYED_HIM = 5
class Player(metaclass = ABCMeta):
def __init__(self):
self.score = 0
self.last_score = None
self.generator = self.play()
def award(self, points):
se... |
import copy
from hash_table import HashTable
def one_away(s1, s2):
if s1 == s2:
return True
len_diff = len(s1) - len(s2)
if abs(len_diff) > 1:
return False
if len_diff == 0:
for i in range(len(s1)):
if s1[i] != s2[i]:
sc = s1[:i] + s2[i] + s1[i+1:... |
mat1 = [[1,2,3],[4,5,6]]
mat2 = [[7,8,9],[6,7,3]]
result= [[0,0,0],[0,0,0]]
for i in range(len(mat1)):
for j in range(len(mat2[0])):
for k in range(len(mat2)):
result[i][j]+= mat1[i][k]*mat2[j][k]
for r in result:
print(r)
|
"""
R 1.12
---------------------------------
Problem Statement : Python’s random module includes a function choice(data) that returns a
random element from a non-empty sequence. The random module includes
a more basic function randrange, with parameterization similar to
the built-in range function, that return a random... |
"""
R 1.3
---------------------------------
Problem Statement : Write a short Python function, minmax(data), that takes a sequence of
one or more numbers, and returns the smallest and largest numbers, in the
form of a tuple of length two. Do not use the built-in functions min or
max in implementing your solution.
Autho... |
class Tile(object):
def __init__(self, letter, points):
self.letter = letter
self.points = points
def __eq__(self, other):
return self.letter == other.letter and self.points == other.points
def __str__(self):
string = self.letter + " " + str(self.points)
return stri... |
import requests
import os
import json
from typing import List
class Spotify:
def __init__(self, user_id: str, auth_token: str):
self.user_id = user_id
self.auth_token = auth_token
def read_playlists(self):
""" Returns all the playlist data for a user. """
url = "https://api.s... |
import sqlite3
from sqlite3 import Error
def create_connection(db_file):
""" create a database connection to the SQLite database specified by db_file
:param db_file: database file
:return Connection object or None"""
try:
conn = sqlite3.connect(db_file)
return conn
except Error as ... |
import math
num=int(input())
print(" ")
for i in range(1,int(math.sqrt(num)+1)):
print(i**2)
|
import torch
# 2.2.4 运算的内存开销
# 索引操作不会开辟新内存,像y = x + y这样的运算是会新开内存的,然后将y指向新内存。
x = torch.tensor([1, 2])
y = torch.tensor([3, 4])
id_before = id(y)
y = y + x
print("执行y = y + x运算前后y的id是否一致:" + str(id(y) == id_before))
print("----------------------------------------------")
# 如果想指定结果到原来的y的内存,我们可以使用前面介绍的索引来进行替换操作。
# 在下面的例子... |
import torch
# 一、算数操作
# 加法
# 1.直接相加
x = torch.rand(5, 3)
y = torch.rand(5, 3)
print("x + y = " + str(x + y))
# 2.torch.add
print("x + y = " + str(torch.add(x, y)))
# 3. 指定输出
result = torch.empty(5, 3)
torch.add(x, y, out=result)
print("x + y = " + str(result))
# 4.inplace
# adds x to y
y.add_(x)
print("x + y = " + ... |
def find_max_min(x):
minimum = maximum = x[0]
for i in x[1:]:
if i < minimum: #check if element is lowest
minimum = i
else:
if i > maximum: maximum = i#check if element is largest
a=int(minimum) #convert minimum element to int
b=int(maximum) #convert max element... |
class Account:
def __init__(self,accountNumber: int,firstName: str,lastName: str,accountBalance: float):
self.accountNumber = accountNumber if accountNumber>10001 else 0
self.firstName = firstName
self.lastName = lastName
self.accountBalance = accountBalance if accountBalance>0 else ... |
from tkinter import *
from tkinter import messagebox, Entry
hourlySalary = [150.00,200.00,250.00]
def calcSalary():
hoursWorked = e.get()
taxRate = tax.get()
grossPay = hoursWorked*hourlySalary[skill.get()-1]
incomeTax = grossPay*taxRate/100
netPay = grossPay - incomeTax
messagebox.showinfo("Sa... |
import re
pattern = re.compile(r'[aeiouAEIOU]')
str1 = input('Enter a string to count vowels present in it:')
print('Number of vowels in the entered string is ' + str(len(pattern.findall(str1))))
|
# -*- coding: utf-8 -*-
class Jogador():
def __init__(self, nome):
self.pontos = 0
self.nome = nome
self.desistir = False
def zerarPontuacao(self):
self.pontos = 0
self.desistir = False
def aumentarPontuacao(self, valor):
self.pontos += valor
d... |
"""This module makes the actual call to the USGS service and it is used by the
main script. The functions get_alert_info and get_available levels only read
local files. The get_earthquake function makes a call to a third party service
and an internet connection is required."""
import requests
import datetime
import js... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Time-stamp: <2016-09-19 06:40:08 cp983411>
import sys
def count_lines_words(text):
""" input:
text: a string
output:
number of lines and words in text """
nlines, nwords = 0, 0
for line in text:
nlines += 1
nwords += len... |
from PIL import Image
import os
def jpg_to_png(folder):
for infile in os.listdir(folder):
print "infile:" , infile
outfile = os.path.splitext(infile)[0] + '.png'
print "outfile:" , outfile
if infile !=outfile:
try:
Image.open("../PythonLearning/CV_sampleI... |
# coding: utf-8
# In[3]:
import numpy as np
import pandas as pd
import numpy as np # import numpy for later use in this tutorial.
import matplotlib.pyplot as plt
pd.__version__
# Pandas objects: Pandas objects can be thought of as enhanced versions of NumPy structured array in which rows and columns are ident... |
#TO RUN: just type python geoDistance.py
import geoip2.database
from math import radians, cos, sin, asin, sqrt
# This creates a Reader object to read from the file
reader = geoip2.database.Reader('GeoLite2-City.mmdb')
#reads off the IPs and puts them in a python list
targets = open("targets.txt")
ip_list = targets.re... |
# For reading data set
# importing necessary libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# reading a csv file using pandas library
wcat=pd.read_csv("E:\\Bokey\\Excelr Data\\Python Codes\\all_py\\Simple Linear Regression\\wc-at.csv")
wcat.columns
plt.hist(wcat.Waist)
... |
# 리스트, 튜플
# 리스트(순서o, 중복, 수정과 삭제 가능)
# 선언
a = []
b = list()
c = [1,2,3,4]
d = [1,100,'pen','cap','plate']
e = [1,100,['pen','cap','plate']]
print(d[3])
print(d[-1])
print(d[0]+d[1])
print(d[3] + d[4])
print(e[2][2])
print(e[-1][-3])
print('===='*20)
print(d[0:3])
print(d[2:])
print(e[2][0:2])
print... |
class Node(object):
"""
LRU Cache node which keeps track of key, value, previous and next nodes
"""
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
self.prev = None
def setNext(self, node):
self.next = node
def setPrev(... |
#!/usr/bin/env python3
""" Created: Average Joe
Simple dice game """
#import stuff
#from cheatdice import Player
from cheatdice import Cheat_Swapper
from cheatdice import Cheat_Loaded_Dice
def main():
""" execute teh main logic """
cheater1 = Cheat_Swapper() #create player object1
cheater2 = Cheat_L... |
from time import sleep
def password():
tries = 0
while tries < 3:
pin = int(input("Please enter your pin in the screen "))
if pin == (1234):
print("Correct..fetching your data in a few seconds...")
return True
else:
print("Incorrect password, please tr... |
# create a new file Warmups.py
# 12.4.17
# Write a Python Function
# which accepts the user's
# first and last name
# and prints them in reverse order
# with a space between them.
# def reverse_order(first_name, last_name):
# # print("%s, %s" % (last_name, first_name))
# print(last_name + " " + first_name) ... |
# This is a guide of how to make hangman
# 1. Make a word bank - 10 items
# 2. Select a random item to guess
# 3. Take in a letter and add it to a list of letters_guessed
# 4. Hide and reveal letters
# 5. Create win and lose conditions
import random
import string
import sys
alphabet = string.ascii_lowercase
words_phras... |
print("Hello, this is a money calculator that calculates how much your money will increase in how many years if an interest percentage is some amount.")
def CalcCurrYearMoney(money,percentage):
i=percentage/100
i = i+1
money = money*i
return money
def main():
x = int(input("please inser... |
def check(n):
add=0
while n>0:
add += n%10
n = n/10
z=add
if z <10:
return z
elif z >= 10:
f=check(z)
return f
k = int(input())
h = check(k)
if h < 10:
if h == 7:
print "The number is a lucky number"
else:
print "The number is not a lucky number"
|
var=raw_input()
i=0
l=0
var=var.upper()
#print var
while i<len(var):
if var[i]!=" ":
#print ord(var[i])-64
l=l+ ord(var[i])-64
"""if var[i]==" ":
l=l-4"""
i=i+1
print l
|
# Exercise 1
class Bus(object):
counter = 0
def __init__(self, seats, color, bus_driver):
self.seats = seats
self.color = color
self.bus_driver = bus_driver
Bus.counter += 1
def change_color(self, recolor):
self.color = recolor
# Today's date
from datetime import d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
count1 =0
count2 =0
cand1 =0
cand2=1
for x, n in enumerate(nums):
if n == cand1:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Solution:
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
cursize = 0
maxsize = 0
rl = len(height)
l = 0
r = rl -1
while l < r:
cursize = abs(r-l) * ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Solution:
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
r = []
c = []
for x in range(len(matrix)):
for y i... |
from termcolor import *
import time
import random
class FinalBoss(object):
def __init__(self, user):
self.user = user
def colorize(self, text, color='red'):
text = colored(text, color, attrs=['bold'])
return text
def typeWriter(self, text, isColored=False, lag=0.005, color='red'... |
mix = ['magical unicorns', 19, 'hello', 98.98, 'world']
integers = [2, 3, 1, 7, 4, 12]
words = ['magical', 'unicorns']
def typeList(arr):
string = ""
sum = 0
stringCount = 0
numCount = 0
for i in range(0, len(arr)):
if type(arr[i]) is str:
string += arr[i]
stringCount += 1
if type(arr[i]) is int:
sum... |
from random import randint
def scoresGrades(end):
for i in range (0, end):
num = randint(60, 100)
if (num < 70):
print("Score: " + str(num) + "; Your grade is D")
elif (num < 80 and num >= 70):
print("Score: " + str(num) + "; Your grade is C")
elif (num < 90 and num >= 80):
print("Score: " + str(num... |
"""
Program: get_user_input.py
Author: Donald Butters
Last date modified: 10/5/2020
The purpose of this program is prompt a name, age, and hourly pay.
Then the program out prints the input as a string
"""
def get_user_input(): # keyword def with function name then ():
"""Prompts the user for name, age and prin... |
#!/usr/local/bin/python
days = 365
numPeople =23
prob = 0
while prob < 0.5:
numPeople += 1
prob = 1 -((1-prob)*(days-(numPeople-1))/days)
print("Number of people:",numPeople)
print("Prob. of same birthday:",prob) |
from functools import wraps
def thisIsliving(fun):
@wraps(fun)
def living(*args,**kw):
return fun(*args,**kw)+ 'living is eating'
return living
@thisIsliving
def whatIsLiving():
"what is living"
return "mygod,what is living,"
print whatIsLiving()
print whatIsLiving.__doc__ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.