text stringlengths 37 1.41M |
|---|
'''
Description: A program that implements the Python turtle library to draw a tree.
(I did not discuss this assignment with anyone.)
Written By: Anh Mac
Date: 11/6/2018
'''
from turtle import *
# I've implemented this function for you; do not edit it.
def tree( trunkLength, angle, levels ):
left(90)
sideways... |
#Chapter 5 - Challenge 1
#Chris Looney
#November 10,2014
import random
first_word = input("Please enter your first word: ")
second_word = input("Please enter your second word: ")
third_word = input("Please enter your third word: ")
fourth_word = input("Please enter your fourth word: ")
fifth_word = input("Please ente... |
#string_value.join(list_name)
list_1 = ["I", "am" , "learning", "python"]
outputStr ="_".join(list_1)
print(outputStr)
#string functions
var ="Learn python"
print(var.title()) #converts first letter of each word into upper case and others to lower case
print(var.swapcase()) #upper case to lower case and vice v... |
#find the sum of 2 binary numbers:
def addBinary( a, b):
length = max(len(a),len(b) + 1)
sum = ['0' for i in range(length)]
if len(a)>len(b):
b= '0' * (len(a)-len(b))+b
elif len(b)>len(a):
a = '0' * (len(b)-len(a))+a
carry = 0
i = len(a)-1
while i>=0:
if int(a[i])+... |
target_list = input().split()
command = input()
while not command == "End":
what, where, how = command.split()
if what == "Shoot":
if len(target_list) >= int(where) >= 0:
target_list[int(where)] = int(target_list[int(where)]) - int(how)
if int(target_list[int(where)]) <= 0:
... |
list_with_numbers = input().split()
list_with_numbers = [int(num) for num in list_with_numbers]
average_number = sum(list_with_numbers) / len(list_with_numbers)
greater_that_average = [num for num in list_with_numbers if num > average_number]
if len(greater_that_average) == 0:
print('No')
else:
greater_that... |
password = input()
line = input()
while not line == "Done":
line = line.split()
command = line[0]
if command == "TakeOdd":
old_password = password
password = ""
for i in range(len(old_password)):
if not i % 2 == 0:
password += old_password[i]
pr... |
word = input()
dictionary = {}
for i in range(len(word)):
if word[i] == " ":
pass
elif word[i] not in dictionary:
dictionary[word[i]] = 1
else:
dictionary[word[i]] += 1
for char in dictionary:
print(f"{char} -> {dictionary[char]}") |
number = int(input())
start = 97
end = start + number
for i in range(start, end):
for j in range(start, end):
for k in range(start, end):
print(f'{chr(i)}{chr(j)}{chr(k)}') |
start = int(input())
second_num = int(input())
end = start * second_num
multiples_list = []
for i in range(start, end + 1, start):
multiples_list.append(i)
print(multiples_list) |
import sys
num_1 = int(input())
num_2 = int(input())
num_3 = int(input())
def small(num_1, num_2, num_3):
smallest_of_all = sys.maxsize
if num_1 <= smallest_of_all:
smallest_of_all = num_1
if num_2 <= smallest_of_all:
smallest_of_all = num_2
if num_3 <= smallest_of_all:
smalles... |
list_with_elements = input().split()
list_with_elements = [int(el) for el in list_with_elements]
while True:
user_input = input()
if user_input == "end":
break
user_input = user_input.split()
command = user_input[0]
if command == "swap":
first_element = int(user_input[1])
... |
happiness_list = input().split()
happiness_multiply = int(input())
multiplied_happiness_list = []
for every in happiness_list:
multiplied_happiness_list.append(int(every) * happiness_multiply)
border = sum(multiplied_happiness_list) / len(multiplied_happiness_list)
happy_employees = [employee for employee in mu... |
# Create calculate_insurance_cost() function below:
def calculate_insurance_cost(name, age, sex, bmi, num_of_children, smoker):
estimated_cost = 250*age - 128*sex + 370*bmi + 425*num_of_children + 24000*smoker - 12500
message = "The estimated insurance cost for " + name + " is " + str(estimated_cost) + " dollars."... |
'''
Author: Michele Alladio
es:
Dato un albero etichettato con numeri naturali, scrivere una funzione
nodeNumber() che restituisca il numero dei nodi
'''
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data): #rico... |
import sys
class Triangle:
def __init__(self, a, b , c):
self.a = int(a)
self.b = int(b)
self.c = int(c)
def isValid(self):
return (self.a + self.b > self.c) and (self.a + self.c > self.b) and (self.b + self.c > self.a)
class TriangleParser:
def __init__(self, datas):
self.datas = datas
def getTriangl... |
# Path setup - do not modify
from inspect import getsourcefile
import os.path as path, sys
current_dir = path.dirname(path.abspath(getsourcefile(lambda:0)))
sys.path.insert(0, current_dir[:current_dir.rfind(path.sep)])
class Solution:
def mergesort(self, arr: list , begin: int, end: int) -> list:
if len(ar... |
random_list = [19, 2, 31, 45, 6, 11, 121, 27]
def bubble_sort(nums):
# по умолчанию от меньшего к большему
swapped = True # чтобы цикл запустился хотя один раз
while swapped:
swapped = False
for i in range(len(random_list) - 1):
if nums[i] < nums[i+1]:
nums[i... |
# Take a number and display its factors
import sys
if len(sys.argv) < 2:
print("Number required!")
exit(0)
num = int(sys.argv[1])
for i in range(2, num // 2 + 1):
if num % i == 0:
print(i, end=' ')
|
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} - {self.age}"
def __eq__(self, other):
return self.name == other.name and self.age == other.age
def __hash__(self):
return self.age
# def _... |
# Function to print table for the given number
def print_table(num, length):
for i in range(1, length + 1):
print(f"{num:2} * {i:2} = {i * num:4}")
print_table(15, 5) # Call function using positional arguments
print_table(length=5, num=23) # Using keyword arguments
|
a = int(input())
b = int(input())
if a>b:
a,b = b,a
for i in range(b,0,-1):
if a%i==0 and b%i==0:
print('gcd of',a,'and',b,'is',i)
break
|
#Leia uma temperatura em Cº e apresente ela em F
#formula f = c*(9.0/5.0) + 32.0
c = float(input("Digite a temperatura em graus Celsius: "))
f = c*(9.0/5.0) + 32.0
print("Valor em Fahrenheit: %.2f"%f,"º") |
from Shapes import *
from Node import *
class Projection(object):
def __init__(self, mini, maxi):
""" Create the projection with it's two values: min, max"""
self.min = mini;
self.max = maxi;
def overlap(self, p2):
""" Check if this projection overlaps with the passed one"""
... |
#7/12/21
import csv
#for reference
header = [["Time", "Velocity", "Wheel Angle", "Push Button", "X Pose", "Y Pose", "Z Orien", "X PF", "Y PF", "Z Orien PF"]]
#2D list to store all the values in
csv_data = []
app_folder = 'Data_Collection/'
def flip_data():
#cut the header off to more easily manipulat... |
import streamlit
import streamlit as st
from pororo import Pororo
summa = Pororo(task='text_summarization', lang='ko')
def summaizer(text):
global summa
output = summa(text)
return output
def write_header():
st.title('Korean Text Summarizer')
st.markdown('''
- Paste any article in the t... |
inventory=[]
max_hp=150
hp=150
name=""
hero_class= ""
attack = 6
defense = 6
n_turn = 0
xp=0
lv=1
#Intro
name=input("---- AVANTIA'S ADVENTURE ----\nFor those who love a good adventure\n\nWrite your hero's name to Start\n-")
print("KASSANDRIA: It's a pleasure to meet you finally, {}. My name is Kassandria, Queen of Ava... |
"""Is Temer still president of Brazil?
Simple Flask app that returns a text response stating
if Michel Temer is still president of Brazil.
"""
from flask import Flask
import president_fetcher
app = Flask(__name__)
@app.route('/')
def isTemerPresident():
"""Returns if Michel Temer is president of Brazil"""
pr... |
'''
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99.
Find the largest palindrome made from the product of two 3-digit numbers.
'''
largest_palindrome = 0
for i in range (100,999):
for j in range (100,999):
number = i * j
number_... |
# https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/529/week-2/3299/
class Solution:
def stringShift(self, s: str, shift: List[List[int]]) -> str:
all_shift = 0
for i in shift:
if i[0]:
all_shift += i[1]
else:
all_shift -=... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
def traverse(root, path):
if not... |
n=int(input("enter the no of terms "))#input from the user
a=int(input("enter the first number "))#input from the user
b= int(input("enter the second number "))#input from the user
i=2 #i is initialised from 2 because we have taken two elements of the fibonacci already
print(a)
print(b)
while(i<n):
... |
#coding=utf-8
from Tkinter import *
'''
#RadioButtonTest
root = Tk()
# label = Label(root,text='Hello,Tknter')
# label.pack()
label = Label(root,text='RadioButtonTest')
label.pack()
#Vn means default choic from all riadiobutton
V1 = IntVar()
V1.set(1)
V2=IntVar()
V2.set(2)
V3=IntVar()
V3.set(3)
V4=IntVar()
V4.set(4... |
class Stack(object):
def __init__(self, count):
self.__count = count
self.__content = [None for _ in range(count)]
self._cursor = 0
@property
def is_empty(self):
return self._cursor == 0
@property
def is_full(self):
return self._cursor == self.__count
d... |
class TrieNode(object):
def __init__(self):
self.passed = 0
self.end = 0
self.next_node = {}
class TrieTree(object):
def __init__(self):
self._head = TrieNode()
def add(self, string):
tmp = self._head
tmp.passed += 1
for s in string:
nex... |
class UnionFindSet(object):
"""
并查集,使用O(1)的时间来判断两个元素是否在同一个集合中。
"""
def __init__(self, iterable):
self._size = {}
self._parent = {}
for i in iterable:
self._parent[i] = i
self._size[i] = 1
def is_same_set(self, item1, item2):
if self._parent.ge... |
class BinaryTree:
def __init__(self, root):
self.root = root
self.result = []
def depthFirstPreOrderTraverse(self):
self.__preDFT(self.root)
return ','.join(self.result)
def __preDFT(self, node):
if node == None:
return
self.result.append(node.da... |
class SinglyLinkedList:
head = None
tail = None
length = 0
def __init__(self):
pass
class Node:
def __init__(self, data):
self.data = data
self.next = None
def toString(self):
tmp = self.head
result = []
for i in range(self.lengt... |
import unittest
from disJointSetTree import DisJointSetTree
class DisJointSetTreeTest(unittest.TestCase):
def setUp(self):
self.set = DisJointSetTree()
def test_makeSet(self):
self.set.makeSet(0)
self.set.makeSet(1)
self.set.makeSet(2)
self.set.makeSet(3)
self.s... |
class Stack:
head = None
size = 0
class Node:
next = None
def __init__(self, data):
self.data = data
def toString(self):
tmp = self.head
result = []
for i in range(self.size):
result.append(str(tmp.data))
tmp = tmp.next
... |
import unittest
from hashSet import HashSet
class Phone:
def __init__(self, number, name):
self.number = number
self.name = name
def hash(self):
return int(self.number[:3])
def equals(self, obj):
return self.number == obj.number
class HashSetTest(unittest.TestCase):
... |
# zip function
# zip function are used zip two lists
# it awlays returns tuples
l1=[1,2,3,4]
l2=[5,6,7,8]
new_list=[]
'''last_name=[10,11,14,17]
l3=list(zip(l1,l2,last_name))
print(l3)'''
#l=[(1,2),(3,4),(5,6),(7,8)]
#print(list(zip(*l)))
'''l1,l2=list(zip(*l))# list unpacking
print(list(l1))
print(list(l2... |
#first_name= "koushik"
#last_name= "bose"
#full_name= first_name+ " " + last_name
#print(full_name)
#print(first_name + str(7))
#print(first_name+"7")
#print(first_name*7)
#print(first_name*7)
#print("\n")
#name=input("enter your name: ")
#print(" hello\t " + name)
#age=(input("enter your age : "))
#prin... |
from functools import wraps
# new functionality in decoraters
def function_data(function):
@wraps(function)
def wrapper(*args,**kwargs):
print(f" you are calling {function.__name__} ")
print(f"{function.__doc__}")
return function(*args,**kwargs)
return wrapper
@function... |
# tuple data structure
# tuple can store any data type
# most important tuple are immutable,once tuple is created you can't update
# data inide tuple
# no append ,no insert,no pop,no remove methods() available in tuple()
# tuple are faster than list
# count,index
# length function
# slicing
#print(dir(tuple... |
import sys
def main():
count = int(input())
numbers = list()
for i in range(2, count + 2):
numbers.append(int(input()))
case = 1
for num in numbers:
issue_checks(num, case)
case += 1
def issue_checks(num, case_num):
digits = list(int(d) for d in str(num))
result ... |
"""
Author: Manasi Gund
Source: CodeChef
Link: https://www.codechef.com/problems/PALIN
"""
def get_middle(number):
mid = int(len(number) // 2)
if len(number) % 2 == 0:
return mid - 1, mid
else:
return mid, mid
def next_palindrome(number):
if number == '9' * len(number):
retur... |
"""
$5 + 10 CHF = $10 if rate is 2:1
$5 + $5 = $10
Return Money from $5 + $5
Bank.reduce(Money)
Reduce Money with conversion
Reduce(Bank, String)
Sum.plus
Expression.times
"""
from unittest import TestCase
from abc import abstractmethod
class Expression(object):
@abstractmethod
... |
num1 = input("enter number 1")
num2 = input("enter number 2")
print("before swapping")
print("num1=" , num1)
print("num2=" , num2)
num1 = num1 + num2
num2 = num1 - num2
num1 = num1-num2
print("after swapping")
print("num1=" , num1)
print("num2=" , num2)
|
## TODO: define the convolutional neural network architecture
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
# can use the below import should you choose to initialize the weights of your Net
import torch.nn.init as I
class Net(nn.Module):
def __init__(sel... |
while True:
text = input("Insert Regular Text And Turn It Into Semi Russian: ")
russianText = ""
for i in text:
if i == "A":
letter = "A"
elif i == "a":
letter = "a"
elif i == "a":
letter = "a"
elif i == "B":
letter =... |
from string import ascii_lowercase, digits
from hashlib import md5
def sanitize_channel_name(name: str) -> str:
whitelist = ascii_lowercase + digits + "-_"
name = name.lower().replace(" ", "-")
for char in name:
if char not in whitelist:
name = name.replace(char, "")
while "--" i... |
#!/usr/bin/env python
"""
Spy snippets
============
You've been recruited by the team building Spy4Rabbits, a highly advanced search engine used to help fellow agents discover files and intel needed to continue the operations against Dr. Boolean's evil experiments. The team is known for recruiting only the brightest r... |
import time
def bubble_sort(a):
n = len(a)
start_time=time.time()
for i in range(n):
for j in range(0,n-i-1):
if (a[j]>a[j+1]):
a[j],a[j+1]=a[j+1],a[j]
end_time=time.time()
print("the sorted array is :",a)
print("The time taken is : ",time.time()-start_time)
... |
## step 3.2 Re-organize the Terms by Topic (5pts)
# You are asked to re-organize the terms by 5 topics.
# For the i-th topic, you should create a file named topic-i.txt.
# Separate each line in word-assignment.dat by topics assigned to them.
# For example, the lines in word-assignment.dat can be considered as the fo... |
with open("Erik/inputs/input01.txt") as f:
partsList = []
for line in f:
partsList.append(int(line.strip()))
def fuelCalc(weight):
return (weight // 3) - 2
def recFuelCalc(weight):
addedFuel = fuelCalc(weight)
totalFuel = addedFuel
while(addedFuel > 8):
addedFuel = fuelCalc(ad... |
import random
# Choisir un nombre aléatoire
nb_choisi = random.randint(0, 100)
print(nb_choisi)
# Demander un nombre
nb_donne = input("Veuillez enter un nombre compris entre 0 et 100:\n")
while int(nb_donne) != nb_choisi:
# si c'est plus grand que le nombre choisi
if int(nb_donne) > nb_choisi:
# Dire q... |
print("CURS 1 - TEMA - Variabile si structuri conditionale\n")
# PENTRU A TRECE LA URMATORUL PUNCT DOAR
# INTRODUCETI next :)
# 1
print("EX 1 - SIR DE NUMERE SAU DE CARACTERE? \n")
nume = input("Numele tau este: ")
while True:
text = input("Textul pe care vrei sa il verifici este: ")
if text == "next":
... |
import pandas as pd
df = pd.read_csv('/Users/oklesing/Desktop/Tensorflow-Bootcamp-master/00-Crash-Course-Basics/salaries.csv')
# Get column Salary from dataframe
salary = df['Salary']
print(salary)
# Get columns Salary and Name from dataframes
# For multiple columns use array
salary_name = df[['Salary', 'Name']]
pri... |
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
import pandas as pd
data = np.random.randint(0, 100, (10, 2))
scalar_model = MinMaxScaler()
#############################################
# Fit to training data #
# Transform to... |
#!/usr/bin/env python3
"""
stack.py - Stack Implementation
Author: Hoanh An (hoanhan@bennington.edu)
Date: 10/18/2017
"""
class Node(object):
"""
Model Node as a class.
"""
def __init__(self, value, next=None):
"""
Create an instance of Stack.
:param value: The value of ... |
#!/usr/bin/env python3
"""
linked_list_test.py - Linked Listed UnitTest
Author: Hoanh An (hoanhan@bennington.edu)
Date: 10/18/2017
"""
from linked_list import *
import unittest
class TestLinkedList(unittest.TestCase):
def test_insert_to_front_empty_list(self):
linked_list = LinkedList(None)
l... |
"""
[2, 3, 6] -> [2, 3, 7]
[9, 9, 9] -> [1, 0, 0, 0]
"""
# def add_one(given_array):
# carry = 1
#
# for index in range(len(given_array))
#
if __name__ == '__main__':
temp_array = []
for i in range(5):
temp_array.append(0)
print(temp_array) |
"""
Assign Numbers in Minesweeper
Implement a function that assigns correct numbers in a field of Minesweeper, which is represented as a 2 dimensional array.
Example:
The size of the field is 3x4, and there are bombs at the positions [0, 0] (row index = 0, column index = 0) and [0, 1] (row index = 0... |
# 古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子
# 假如兔子都不死,问每个月的兔子总数为多少?
m = input('月份:')
if m == 1:
rabbits = 1
elif m == 2:
rabbits = 1
else:
rabbits = (1 / (5 ** 0.5)) * (((1 + (5 ** 0.5)) / 2) ** m - ((1 - (5 ** 0.5)) / 2) ** m)
print(rabbits)
|
#一个数如果恰好等于它的因子之和,这个数就称为"完数"。例如6=1+2+3.编程找出1000以内的所有完数。
for i in range(1,1001):
list = []
for j in range(1,i):
if i % j == 0:
list.append(j)
sum_list = sum(list)
if sum_list == i:
print(i)
|
# 利用递归方法求5!。
def factorial(n):
if n == 1:
fn = 1
else:
fn = n * factorial(n - 1)
return fn
print(factorial(5))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pymysql.cursors
import classe as cl
# connection to the database
conn = pymysql.connect(host='localhost', user='root', passwd='', db='Openfoodfacts', charset='utf8')
cursor = conn.cursor()
def select_categories(dict_categories):
category0 = ("ve... |
#팩토리얼 프로그램
fac=int(input("숫자를 입력하세요."))
sum1=0
for i in range(1,fac+1,1):
sum=sum*i
print(sum1) |
# 참석자에 맞추어서 치킨(1인당 1마리), 맥주(1인당 2캔),
# 케익(1인당 4개)를 출력하는 프로그램을 작성해보자.
cham=int(input("참석자를 넣어주세요"))
ch=cham*1
beer=cham*2
cake=cham*4
print("치킨=",ch, "마리")
print("맥주=",beer,"잔")
print("케익=",cake, "개")
|
# Variables of different types
# 기본형 타입
b=True
i=1
f=0.1
c="c"
str="hello"
n=None
# 변수 타입 확인
print("b", type(b))
print("i", type(i))
print("f", type(f))
print("c", type(c))
print("str", type(str))
print("n", type(n))
# 복합형 타입
set1=set([1,2,3,1,2])
set2=set("Hello")
l=[0,1,2,0,3]
t=(0,1,2)
d={0:"Zero"}
# 변수 타입 확인
|
import random
from overlap import isOverlapR2
def newrandom():
'''
used to generate sample and process some controled testing
'''
def getRandom(min,max):
for m in range(2):
(a,b)=random.randint(min, max),random.randint(min, max)
(c,d)=random.randint(min, max),random.randint... |
# https://leetcode.com/problems/richest-customer-wealth/
def rich_customer(accounts):
max_wealth = 0
for customer in accounts:
new_wealth = sum(customer)
if new_wealth > max_wealth:
max_wealth = new_wealth
return max_wealth
print(rich_customer([[1, 2, 3], [3, 2, 1]]))
print(ric... |
# https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/
def kids_with_candies(candies, extraCandies):
original_greatest = max(candies)
output = list()
for original in candies:
updated_candies = original + extraCandies
output.append(updated_candies >= original_greatest)
... |
def print_comments():
"""check if a phrase is correct in respect to parenthesis openings and closings"""
with open('a_cpp_file.cpp', 'r') as file:
data = file.read()
to_print = ''
should_print = False
for i, char in enumerate(data):
if i > 1:
if data[i-1] == '*' and dat... |
print('This calculator will change the temperature from Fahrenite to Celcius. Check it out!\nTemperature in Fahrenheit!')
temp_nite = int(input())
def convert_temp(nite):
return ((temp_nite - 32) * 5/9)
def converted_temp(cel):
return "The temperature is {} in celcius.".format(cel)
result = convert_temp(temp_... |
INF = float('inf')
class Card:
def __init__(self, s, v):
self.suit = s
self.value = v
def merge(A, left, mid, right):
n1 = mid - left
n2 = right - mid
L = [A[left + i] for i in xrange(n1)] + [Card('', INF)]
R = [A[mid + i] for i in xrange(n2)] + [Card('', INF)]
i = j = 0
... |
print("Var bor du")
land = input()
Norden = ["Sverige", "sverige", "Norge", "norge", "Finland", "finland", "Danmark", "danmark", "Island", "island"]
Storbritanien = ["England", "england", "Wales", "wales", "Nordirland", "nordirland", "Skottland", "skottland"]
if land in Norden: #om din input är finns i listan norden:... |
import requests
print("Skriv in namn på stad")
city = str(input()) #gör inputen till en string
cities = [ #städer i sringern
"stockholm",
"uppsala",
]
if city.lower() in cities:
forecasts = requests.get('https://54qhf521ze.execute-api.eu-north-1.amazonaws.com/weather/' + city.lower()).json()["forecasts... |
#coding:gb2312
#ʹpop()del()бɾ
names=['cby','lyl','fjy','hl','sch']
message_1="Since the reserved table could not be delivered in time, I could only invite two guests."
print(message_1)
message_2="I'm So Sorry I Can't Have Dinner With You"
popped_names=names.pop(-1)
print(popped_names.title()+", "+message_2+"!")
popped_... |
#coding:gb2312
#ifϰ1
#if-else
alien_color='yellow'
if alien_color=='green': #==ȣ=鲻
print("һ÷5")
else:
print("һ÷10")
#if-elif-else
alien_color='red'
if alien_color=='green':
print("÷5")
elif alien_color=='yellow':
print("һ÷10")
else:
print("һ÷15")
|
#coding:gb2312
#ifѧϰ
#if䣬ִеһ
print("if䣺\n")
age=18
if age>=18: #ifforеҪðţһжҪ
print("You are old enough to vote!") #ifͨˣŻִifĵĴ
print("Have you registersd to vote yet?")
#if-else
print("\n\nif-else䣺\n")
age=17
if age>=18:
print("You are old enough to vote!")
print("Have you registersd to vote yet?... |
#coding:gb2312
#if䴦бϰ
#ϰ1
print("ϰ1")
users=['lyl','cby','ft','fjy','cxk'] #5ûб
for user in users: #ûб
if user=='lyl': #ʹǡlylʱһʺϢ
print("Hello Lyl,would you like to see a status report?")
else: #˵ʱһϢ
print("Hello "+user.title()+",thank you for logging in again.... |
#coding:gb2312
#Ƭϰ1
letters=['c','g','j','f','i']
print("The first three items in the list are :")
print(letters[:3])#ͷʼȡ3ֹ
print("\nThe items from the middle of the list are :")
print(letters[1:4])#1ʼȡ4ֹ
print("\nThe last three items in the list are :")
print(letters[-3:])#-3ʼȡĩβֹ
|
#coding:gb2312
#Ԫѧϰ
#Ԫ鿴бԲŶǷʶʵDzɱб
dimensions=(200,50)
#print(dimensions[0])
#print(dimensions[1]) #ͷбʽһ
#dimensions[0]=250 #˴лʾΪԪIJDZֹģpythonܸԪԪظֵΪѧϰ漸дע͵
#ȻԪԪأԸ洢Ԫıֵ
print("Original Dimensions :")
for dimension in dimensions: #Ԫ
print(dimension)
dimensions=(400,100) #洢Ԫı¸ֵ
print("\nModified Dimensions ... |
#coding:gb2312
#ϰforѭ
numbers=['9','6','2','4']
for number in numbers:#for֮ðţҪ
print(number+", "+"is my favorite number"+"!")
print("This is my lucky number "+number+"!\n")
print("I love these numbers"+" !")#56Ķѭһ֣вִֻһ
#ע⣺for֮ðţΪ˸pythonһѭĵһУ©
#½ԼҪģʱҪؿһԼ
|
#coding:gb2312
#ϰ2ʹreplace()ַеضʶ滻Ϊһ
filename = 'python_note.txt'
with open(filename) as f:
lines = f.readlines()
for line in lines:
line = line.rstrip()
print(line.replace('Python', 'C')) #ղǸеÿһ'Python'滻Ϊ'C'
|
#coding:gb2312
#if䴦б
requested_toppings=['mushrooms','green peppers','extra cheese']
for requested_topping in requested_toppings:
if requested_topping=="green peppers":
print("Sorry,we are out of green peppers right now.")
else:
print("Please adding "+requested_topping +"!")
print("\nFinished making pizza.")
#б... |
def math(A , B):
return A + B, A - B, A * B, A // B
A = int(input("Введите число А: "))
B = int(input("Введите число В: "))
if( B == 0 ):
print(f"({A + B},{A - B},{A * B},Ошибка:деление на ноль)")
else:
math(A, B)
print(math(A, B))
|
"""Generate sales report showing total melons each salesperson sold."""
salespeople = [] #creating empty list to use
melons_sold = [] #creating empty list to use
f = open('sales-report.txt') #opens the report
for line in f:
line = line.rstrip() #strips the white space at end of line
entries = line.split('|')... |
#Encoding
# -*- coding: utf-8 -*-
#lista=[1,2,3,4,5,6,7]
#print lista[2]
#print lista[2:5]
#print lista[5:]
#print lista[:5]
#print lista[:]
#m=0
#for i in range(len(lista)):
# if m<lista[i]:
# m = lista[i]
# print i,m
#
#lista.append("adsasd")
#lista.insert(1,'asdasdasdasdfgg')
#print lista
#lista.... |
import re
while True:
regex='^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.w\{2,3})+$'
mail=input("enter your mail:")
if(re.search(regex,mail)):
break
else:
print("please enter valid mail id")
continue
while True:
pas=input("enter your password:")
if len(pas)==6 or len(pas)==7 or len(... |
#Crie um algoritmo que leia um número e mostre o seu dobro, triplo e raiz quadrada.
n = int(input('Digite um número: '))
d = n*2
t = n*3
r = n ** (1/2)
print('O dobro de {} vale {}.'.format(n, d))
print('O triplo de {} vale {}.'.format(n, t))
print('A raiz quadrada de {} vale {}.'.format(n, r))
|
#!/usr/bin/env/python3
""" Keyword in Context
Author: Jinghua Xu
Description: an interface for visualizing keywords in context using tries
Honor Code: I pledge that this program represents my own work.
"""
from kwic.word_matching_trie import WordMatchingTrie
import argparse
if __name__ == "__ma... |
"""
AngryTurtle
2018. 10. 23
동의대학교 컴퓨터 소프트웨어 공학과
20153308 송민광
이미지 출처
병아리 - https://m.blog.naver.com/lovedesign01/150168487961
토끼 - http://m.inven.co.kr/board/powerbbs.php?come_idx=4538&l=3232417&iskin=overwatch
박스 - https://social.lge.co.kr/product/795_/
"""
import turtle
import random
import math
tu... |
"""
Realizar un programa que ordena nombres alfabeticamente. Primero debe pedir al usuario que ingrese el número de nombres que serán ingresados, luego debe pedir al usuario que ingrese un nombre y repetir ese pedido la cantidad de veces indicada. Los nombres se deben ir agregando a una lista. Por último, ordenar la li... |
"""
Escribir una función que chequee los siguientes usuarios y contraseñas:
Usuario: Juan - Contraseña: 12345_
Usuario: Pablo - Contraseña: xDcFvGbHn
La función debe recibir como parámetros el usuario y la contraseña, y debe devolver el valor True o False.
"""
def chequarLogin(user, password):
if (user == "Juan"... |
from static_values import *
# Create a board of size 8x8
BOARD = {}
# "king": 1
# "queen": 2
# "knight": 3
# "bishop": 4
# "rook": 5
# "pawn": 6
TWO_BOARD = [[5, 3, 4, 2, 1, 4, 3, 5],
[6, 6, 6, 6, 6, 6, 6, 6],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0,... |
class Student:
def __init__(self,firstName,lastName,phone):
self.firstName=firstName
self.lastName=lastName
self.phone=phone
def display(self):
print ("First Name:",self.firstName)
print ("Last Name:",self.lastName)
print ("Phone:",self.phone)
class Grade(Student... |
import sys
val1= 'hi'
if (len(sys.argv)>1):
val1=str(sys.argv[1])
def parityOf(int_type):
parity = 0
while (int_type):
parity = ~parity
int_type = int_type & (int_type-1)
if (parity==-1):
return(0)
return(1)
def calcLRC(input):
lrc = ord(input[0])
for i in range(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.