text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python
# -*- coding:utf8 -*-
# author:mafei0728
#带有yield关键字的函数,就是生成器
#生成器本质就是迭代器
from collections.abc import Iterator
def fun():
print('ok')
yield 1 # return 1
# x = fun()
# print(isinstance(x,Iterator)) ##判断为迭代器
# print(next(x))
# 触发生成器,需要用next()方法,遇到yield停止,并返回一个值,再次next()就继续执行,直到报错
def fun2... |
#!/usr/bin/env python
# -*- coding:utf8 -*-
# author:mafei0728
def fun(a,b):
c = type(a)
if c is list:
a.append(b)
if c is str:
a=a+b
if c is int:
a = a+9
print(a)
x=[1,2,4]
y="c"
fun(x,y)
print(x)
g = "a"
f = 'b'
fun(g,f)
print(g)
h = 1
j = 2
fun(h,f)
print(h) |
#!/usr/bin/env python
# -*- coding:utf8 -*-
# author:mafei0728
"""
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customize the sort order, and the
reverse flag can be set to request the result in descending order.
"""
#可迭代对象--到迭代... |
#!/usr/bin/env python
# -*- coding:utf8 -*-
# author:mafei0728
c=dict.fromkeys((1,2,3,4),("a"))
print(c)
print(dict(x='1',y='2'))
print(dict(((1,2),(2,3)))) |
#!/usr/bin/env python
# -*- coding:utf8 -*-
# author:mafei0728
def search_object():
print('查找')
def delete_object():
print('删除')
def add_object():
print('增加')
def change_object():
print('修改')
cmd_dict = {
'search':search_object,
'delete':delete_object,
'add':add_object,
'change':chan... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#异常指程序运行过程中跑出的错误信息
#异常处理就是捕捉异常,进行处理,避免程序退出
# 1:捕捉,处理
try:
print(x)
except NameError as f:
print(f)
x =1
print(x)
#2: 多分子的捕捉处理
dict1 = {
"x":1,
"y":2,
}
try:
print(dict1["z"])
except NameError as f1:
print(f1)
except KeyError as f2:
pri... |
import os
print ("Press 1 to Shutdown Computer")
print ("Press 2 to Restart Computer")
print ("Press any other key to exit this menu")
keypress= int(input("\nEnter Your Choice: "))
if keypress==1:
os.system("shutdown /s /t 1")
elif keypress==2:
os.system("shutdown /r /t 1")
else:
exit()
|
def is_all_unique(s):
"""
Determine if a string contains only unique characters.
"""
lowercase_s = s.lower()
store = dict()
for c in lowercase_s:
if c in store:
return False
else:
store[c] = 1
return True |
import math
def find_cyclically_shifted_min(arr):
"""
Returns index of the smallest element in a cyclically shifted array
"""
low, high = 0, len(arr) - 1
while low < high:
mid = low + (high - low) // 2
if arr[mid] > arr[high]:
low = mid + 1
elif arr[mid] <= ... |
def binary_search_iterative(data, target):
"""
Find target element within data array iteratively.
Precondition: data is sorted
"""
low, high = 0, len(data) - 1
while low <= high:
middle = low + (high - low) // 2
if target == data[middle]:
return True
if targe... |
def recursive_multiply(x, y):
"""
Return product of two positive integers x and y
Requirement: Calculate product without using multiplication operator
"""
if x < y:
return recursive_multiply(y, x)
if y == 0:
return 0
return x + recursive_multiply(x, y - 1) |
import random
def contains(ball,n,balls_code):
for i in range (n):
if(ball==balls_code[i]):
return 1
return 0
#draw the balls
balls_code=[]
ball=0
for i in range(6):
ball = random.randint(0, 7)
while(contains(ball,i,balls_code)):
ball=random.randint(0,5)
balls_code.appe... |
# 範例輸入:hello
# 範例輸出:olleh
# PS. 可以用 str[i] 取得第 i 個字,例如說 str="abc",str[0] 就是 'a'
str = input("pleas enter a word\n") # 讓使用者輸入字串
new_str = "" #建立空字串
for i in range(len(str)-1):
new_str = new_str + str[-(i+1)] # 倒著數字串(避開第0序列)
new_str = new_str + str[0] # 補上第0序列
print(new_str)
|
count = input ("Enter number of times #")
i = 0
while i < int (count) :
print ("Hello")
i= i +1
|
vals= [22,33,44,55,66]
print (vals[1])
print (vals[1:])
print (vals[-3:-1])
print (vals[-3:])
print (len (vals))
vals.append("77")
print (vals)
vals.insert (1,15)
print (vals)
vals.remove("77")# object to be deleted
print (vals)
x= vals.pop(1)#index to be deleted
print (x)
vals.reverse()
print (vals)
vals.sort()
pr... |
import re
mytext = "My name is Tom ,Phone My Office Phone number \\n is [9988554455]." \
"I have a another Phone number 0123456789123 thanks." \
"My offie email is vijeesh.tp@experzlab.com and my personal email is " \
"vijtp@gmail.com"
#res = re.finditer( r"[a-z0-9._]{3,50}@[a-z0-9._]{4,50... |
def readfile (filename) :
data = open (filename)
lines= data.readlines()
return lines
def processdata (lines):
l= []
for x in lines :
vals= x.split(",")
total = int (vals[2])+ int (vals[3])+ int (vals[4])+ int (vals[5])
l.append( (vals[0], vals[1], total ) )
return l
de... |
def calcInterest(term, amt, rate):
res= term*amt/rate/100
return res
def main ():
try:
x = int (input ("Term #"))
y = int (input ("Amoun#"))
z = eval(input ("Interest rate#"))
r = calcInterest(x, y, z)
print(r)
except ValueError as e1:
print("Please pr... |
my_list = [3, 4, 6, 10, 11, 15]
alices_list = [1, 5, 8, 12, 14, 19]
def merge(a,b):
merged = []
i, j = 0, 0
max_i = len(a)
max_j = len(b)
while i < max_i and j < max_j:
if a[i] <= b[j]:
merged.append(a[i])
i += 1
else:
merged.append(b[j]... |
import numpy as np
def abundance(z, bins=10, *args, **kwargs):
"""Calculate the approximate "abundance" of continuous array z values.
The abundance here is an approximation of distinct values across a
multi-dimensional space defined by z. For each observation of z,
the approximate count of similar va... |
#!usr/bin/python
from datetime import date
str=input("enter your name")
a=input("enter your age")
year=(date.today()).year + 95
print(str,",you will turn 95 in year %d" %year)
|
def get_hash(word):
word_hash = {}
string = ""
counter = 1
for char in word:
if char not in word_hash:
word_hash[char] = counter
counter += 1
for char in word:
string += str(word_hash[char])
return string
def findSpecificPattern(Dict, pattern):
result... |
'''
class node:
def __init__(data):
self.data = data
self.next = None
'''
# Method 1: Iterative Approach
def findMid(head):
total, temp = 0, head
if temp is None:
return -1
while temp is not None:
temp = temp.next
total += 1
count, temp = 0, head
wh... |
def longestSubarray(arr, n, k):
# dictionary hash used as hash table
hash = {}
sum, maxLen = 0, 0
for i in range(n):
sum += arr[i]
# when subarray starts from index '0'
if (sum == k):
maxLen = i+1
# make an entry for 'sum' if it is not present i... |
def subarrayTotal(n):
return (n*(n+1))//2
def subarrayCount(n, L, R, arr):
result = 0
# exc - count of elements smaller than L in current valid subarray.
# inc - count of elements smaller than or equal to R.
exc, inc = 0, 0
for i in range(n):
# If the element > R, add... |
class Node:
def __init__(self, data): # data -> value stored in node
self.data = data
self.next = None
def getPoint(head1, head2, diff): # temporary function
# assuming that head1 is bigger
count = 0
while (count < diff):
head1 = head1.next
count += 1
while (head1... |
class Parser(object):
#Definimos los tipos de comandos con estos numeros para darles un valor numerico.
A_COMMAND = 0
L_COMMAND = 1
C_COMMAND = 2
#Constructor.
def __init__(self, infile):
with open(infile, 'r') as file:
self.lines = file.readlines()
self.currentLine =... |
"""
week is even => sat, sun off
week is odd => sat, sun on
alternate three day weekend with mon & fri =>
work three days a week
must work exactly two days in a row:
mon => tue
mon & tue => not wed
not mon & tue => wed
not mon & not tue & not wed => not thu
tue & wed => not thu
tue & not wed =>... |
"""Clicker"""
class BaseClick(object):
def __init__(self, config, v_quantity=1, m_quantity=1):
self._value = config['value']
self._price = config['price']
self._mult = 1
self._mult_max = 10
self._value_max = 100
self._scale = 1.15
self._value_quantity = v_qu... |
# Tensor reshaping
import torch
x = torch.arange(9)
# rearrange x to be a 3x3 matrix
# view and reshape do almost the same thing
# view acts on contigous tensors, stored contiguosly in memory
x_3x3 = x.view(3, 3)
print(x_3x3)
x_33 = x.reshape(3, 3)
# make the transpose of x_3x3 and set it to x
# transpose is a special... |
#!/usr/bin/python
import string
a = open('2.txt').read()
hasil = ''
for i in a:
if i in string.ascii_lowercase or i in string.ascii_uppercase:
hasil += i
print hasil |
phones=[]
class Handphone:
def __init__(self, version, brand, color):
self.version = version
self.brand = brand
self.color = color
def info(self):
print(f"Version: {self.version}\nBrand: {self.brand}\ncolor: {self.color}")
def register(self):
phones.append(self)
while... |
from zipfile import ZipFile
import os
def get_all_file_paths(directory):
file_paths = []
for root, directories, files in os.walk(directory):
for filename in files:
filepath = os.path.join(root, filename)
file_paths.append(filepath)
return file_paths
def zip(dir,zipName):... |
# 1111111111111111111111111111111
class Animal:
name = "Horse"
def __init__(self, name, age):
self.n = name
self.a = age
def display(self):
print(self.n, self.a)
def sound(self, voice):
print(self.n + " speaks " + voice)
# cat = Animal(Animal.name , 4)
... |
from functools import lru_cache
def moves(h):
a, b = h
return (a, b + 1), (a, (b * 3) - 1)
@lru_cache(None)
def game(h):
if sum(h) >= 33:
return 'W'
if any(game(m) == 'W' for m in moves(h)):
return 'P1'
if all(game(m) == 'P1' for m in moves(h)):
return 'B1'... |
"""
>>> diagonal(3, [[11, 2, 4],[4, 5, 6],[10, 8, -12]])
15
"""
def diagonal(n, matrix):
start, end = 0, 1
x, y = [], []
for row in range(n):
for col in range(start, end):
x.append(matrix[row][col])
start += 1
end += 1
start, end = 0, 1
for row in ran... |
# coding: utf-8
"""
>>> solution([1, 3, 6, 4, 1, 2])
5
>>> solution([1, 2, 3])
4
>>> solution([−1, −3])
1
"""
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A):
# write your code in Python 3.6
items = list(set(A))
for index, ... |
from math import sqrt, ceil
highestPrime=0
def prime(num):
if 600851475143%num==0:
isPrime = primeCheck(num)
if isPrime:
print("%d is prime" % num)
def primeCheck(num):
if num%2 == 0:
return False
for i in range(3, ceil(sqrt(num))+1, 2):
if num%i == 0:
return False
return True
def ... |
import sqlite3
from exercise import Exercise
from cohort import Cohort
from student import Student
from instructor import Instructor
class StudentExerciseReports():
"""Methods for reports on the Student Exercises database"""
def __init__(self):
self.db_path = "/Users/dustinmurdock/workspace/python/S... |
board = { '1':' ','2':' ','3':' ',
'4':' ','5':' ','6':' ',
'7':' ','8':' ','9':' '}
def printboard(board):
print(board['1']+ '|'+board['2']+'|'+board['3'])
print('------')
print(board['4'] + '|' + board['5'] + '|' + board['6'])
print('------')
print(board['7'] + '|' + board['8... |
"""
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
1->2->3->4->5->NULL
k = 1: 5->1->2->3->4->NULL
k = 2: 4->5->1->2->3->NULL
k = 3: 3->4->5->1->2->NULL
node_ptr = head
back_ptr = None
while (node_ptr !... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
def dfs(left,right):
if left is None and right is N... |
'''
@summary: Python Intro - Slicing
'''
# ---------------------------
# slicing or accessing members via "array" notation
# ---------------------------
# variable[X] - item X
# variable[fromX:toY]
# variable[fromX:-toY] - "-toY" starting from last
# variable[:toY] - from first
# variable[fromX:]... |
# This program is for the game Pong
# References: Python 3 and Pygame Documentation
# Author: Urvi Patel
import pygame
# User-defined functions
def main():
# initialize all pygame modules (some need initialization)
pygame.init()
# create a pygame display window
pygame.display.set_mode((500, 400))
# s... |
#Yong Da Li
#Saturday, March 2, 2019
#Professor Nebu Mathai
#CSC190
#assignment A - chess player
#test file for decision making tree
from chessPlayer_tree import *
from chessPlayer_board import *
#create Tree node
def test1():
board = Board()
val = board.eval()
player = 10
root = Tree(board, val, 10)
root.prin... |
import unittest # Módulo para realizar las pruebas
import random # Para usar la funcion aleatoria
class RegisterCash:
""" Clase para caja registradora
"""
productPrice = [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000]
product = []
productCode = []
priceSubtotal =[]
de... |
# This file contains general useful functions
def mapInput(input, init_min, init_max, final_min, final_max):
output = ((input - init_min) / (init_max - init_min)) * (final_max - final_min) + final_min
return output
def limit(input_, top_limit, bottom_limit):
if input_ > top_limit:
return top... |
# Thanks for visiting my code. This is a Student Management Program
# I did it with minimal use of tools and resources without functions and OOPS.
# as a Computer Science Project
# Suggest updates if required https://github.com/vyasrudra/basic-student-managementprogram
# time consumed [00h:33m:47s], can run in term... |
import pygame
WindowX=640
WindowY=576
pygame.init()
#Create the main window
screen=pygame.display.set_mode([WindowX,WindowY])
#I placed "import map" here because some of map's functions require an active display
#and an initialized pygame.
import map
#Create a Rect the same size as the screen to use as a camera.
V... |
(python_advanced_features)=
# More Language Features
## Overview
```{tip}
With this last lecture, our advice is to **skip it on first pass**,
unless you have a burning desire to read it.
```
It\'s here
1. as a reference, so we can link back to it when required, and
2. for those who have worked through a number o... |
<!-- (numba)= -->
# Numba
In addition to what\'s in Anaconda, this lecture will need the following
libraries:
!pip install --upgrade quantecon
Please also make sure that you have the latest version of Anaconda,
since old versions are a
{ref}`common source of errors <troubleshooting>`.
Let\'s start with some import... |
"""
This document is created using the reference of official python tutorial
(https://docs.python.org/3/tutorial/).This material is not a complete reference
of python programming language. Here you can find quick reference of python
syntaxs and some of it's basic concepts.
"""
""" Using Interpreter """
# To start in... |
import os
import csv
#set a file path to the budget data
filePath = os.path.join("Resources","budget_data.csv")
#open the budget data csv file, skip the header row
with open(filePath, 'r') as budgetFile:
csvReader = csv.reader(budgetFile, delimiter=",")
header = next(csvReader)
#initialize variables
... |
print ("_" * 80)
nome = input ("Digite o nome do aluno: ")
turma = input ("Digite a turma em que ele está: ")
n1 = float(input("Digite a primeira nota. "))
n2 = float(input("Digite a segunda nota. "))
n3 = float(input("Digite a terceira nota. "))
media = (n1 + n2 + n3)/3
if media < 5:
print('Infelizmente o a... |
import unittest
import math
from typing import List
class TestClass(unittest.TestCase):
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
size1 = len(nums1)
size2 = len(nums2)
## 边界值处理
if size1 == 0 :
return self.median(nums2)
elif si... |
nums = input("Insert a comma-separated list of numbers: ")
nums = nums.replace(' ', '').split(',')
nums = [int(n) for n in nums]
print(nums)
print(tuple(nums)) |
# БСБО-05-19 Савранский Сергей
mark = False
slash = False
char = 0
result = []
for i in range(int(input('N >> '))):
line = input('Line >> ')
while line[char] == " ":
result.append(" ")
char += 1
for j in range(char, len(line)):
if not slash:
if line[j] == "'":
... |
# БСБО-05-19 Савранский Сергей
book = {}
for _ in range(int(input('N >> '))):
name, number = input('Data >> ').split()
if number in book:
book[number].append(name)
else:
book[number] = [name]
for _ in range(int(input('K >> '))):
print(*book.get(input('Name >> '), ['Нет в телефонной кн... |
# БСБО-05-19 Савранский Сергей
food = [input("Food >> ") for i in range(int(input("M >> ")))]
was = []
for i in range(int(input("N >> "))):
was += [input("Food >> ") for j in range(int(input("K >> ")))]
print('\n'.join(list(filter(lambda f: f not in was, food))))
|
# To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns
# %% [markdown]
# ## Load Titanic data
#
# The Titanic dataset was obtained from https://github.com/awesomedata/awesome-public-datasets/blob/master/... |
# %%
import math
from sklearn.metrics import precision_recall_fscore_support
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
from sklearn.neighbors import NearestNeighbors
import random
import itertools
import matplotlib.pyplot as plt
# sklearn.model_selection.tra... |
import os
print(os.getcwd())
# 连接两个目录组成一个新的路径 /
imgpath= os.path.join(os.path.dirname(os.getcwd()),"img\\temp.txt")
f = open(imgpath)
print(f.readline())
f.close()
for i in os.listdir(os.path.dirname(imgpath)):
print(i)
for i in os.listdir(os.path.abspath("../img")):
print(i)
# 取当前的目录的绝对路... |
import os
import sys
print(os.getcwd())
# 复制文件
with open("note/1.1.txt","r") as f, \
open("1.1.txt" ,"w") as f2:
f2.write(f.read())
# Iterable 可迭代的 Iterator (generator) 迭代器
#str list set dict tuple
li = [1,2,3]
a = iter(li)
print(next(a))
print(next(a))
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 20 17:06:02 2018
The Selection sort algorithm is based on the idea of finding the minimum or
maximum element in an unsorted array and then putting
it in its correct position in a sorted array.
@author: Akash
"""
def swap(num1,num2):
temp = num1
num1=nu... |
numberOfWords = input()
for i in range(int(numberOfWords)):
word = input()
if len(word) > 10:
abbreviation = word[0] + str((len(word) - 2)) + word[-1]
print(abbreviation)
else:
print(word)
|
from types import GeneratorType
from functools import wraps
def generator_of(size):
"""this decorator factory turns the input into a generator (if it's not
already so), then process each chunk and yields it as function output."""
def make_chunks(enum):
"""Returns a chunk generator from an enum... |
# Función que devuelve todos los divisores de un número dado
def divisores(n):
if isinstance(n, int) and n >= 1:
resultado = []
for a in range(1, n):
if n % a == 0:
resultado.append(a)
return resultado
else:
return "Error: debe indicar un núme... |
from time import time
class Remaining:
"""calculates the time remaining from the total number of items and the
number of processed items.
>>> import time
>>> c = Remaining(10)
>>> time.sleep(1)
>>> print (c)
0% (0 of 10) (1s elapsed, ~0s remaining)
>>> c.tick()
>>> pr... |
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# load hand written dataset
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
batch_size = 100
n_batch = mnist.train.num_examples // batch_size
x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [N... |
"""
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
count=[]
for _ in texts:
if(_[0] not in c... |
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 24 12:56:38 2018
Author: hamdymostafa
A simple implementation of a hash table in Python that avoids collision.
"""
table = [ [] for _ in range(10)]
def hashing_function(key):
# input: key
# output: index
return key%10
def insert... |
class Stack:
def __init__(self):
self.stack = []
def pop(self) -> int:
return self.stack.pop()
def push(self, val) -> bool:
if val is None:
return False
self.stack.append(val)
return True
myStack = Stack()
myStack.push(1)
myStack.push(2)
m... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 26 16:37:08 2018
@author: sagar
"""
students=[]
def get_student_tittlecase():
student_tittlecase=[]
for student in students:
student_tittlecase.append(student["name"].title())
return student_tittlecase
def print_student_tittl... |
#magic-square of odd-dimension
n = int(input('Enter n:'))
# creating a structure of dim nxn
def magicSquare(n):
magicSqr = []
for i in range(n):
l = []
for j in range(n):
l.append(0)
magicSqr.append(l)
i = 1
p, q = int(n/2), n-1
while (i <= n*n):
if magicS... |
# Snake Water Gun game
import random
str = ['S', 'W', 'G']
user_score, system_score = 0, 0
print('You have 10 moves in total')
i = 1
while i < 11:
print('You have', 11-i, 'moves left')
print('Enter S for Snake')
print('Enter W for Water')
print('Enter G for Gun')
user_choice = input('')
system_c... |
from PIL import Image
import random
end = 100
def show_board():
img = Image.open('snakeandladder.jpg')
img.show()
def check_ladder(points):
if points == 8:
print('Ladder')
return 26
elif points == 21:
print('Ladder')
return 82
elif points == 43:
print('Ladd... |
import csv #importing csv module to read the Sample.csv file
import matplotlib.pyplot as plt #importing module matplotlib to plot histogram
alphabet = [] #declaring a list to store English alphabets
char = 65 #variable containing the ASCII value of 'A'
# Storing the capital letters in list a... |
import calendar
def check_leap(y):
if y%400 == 0 or y%100 != 0 and y % 4 == 0:
return 1
else:
return 0
def check_valid_date(d, m, y, l):
if l == 1: # for February
if m == 2:
if d < 30:
return True
else:
return False
el... |
import hashmap
# creata a mapping of state to abbbreviation
states = hashmap.new()
hashmap.set(states, 'Oregon', 'OR')
hashmap.set(states, 'Florida', 'FL')
hashmap.set(states, 'California', 'CA')
hashmap.set(states, 'New York', 'NY')
hashmap.set(states, 'Michigan', 'MI')
# create a basic set of states and some cities... |
import validationModule
class Student:
def __init__(self):
self.name=''
self.roll=''
def setName(self,name):
self.name=name
def setRoll(self,roll):
self.roll=roll
def getName(self):
return self.name
def getRoll(self):
return self.roll
class Marks(S... |
# def sayHello():
# print("Hello")
# x=sayHello
# x()
def calculator(fn):
def sayHello(x,y):
print("Going to Add 2 numbers")
return fn(x,y)
return sayHello
@calculator
def add(a,b):
print(a+b)
add(2,5) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 6 11:30:07 2020
@author: rhodgson
"""
#Copy the SAM file from shared/week2/ERRetc
#Now write script to convert the SAM file to a BED file
#comparing SAM file format to BED file format
#For each line of my sam file, read it and convert to output ... |
import numpy as np
import sys
from random import choice
class GameState:
def __init__(self):
self.red = {
'positions':[(-3,3), (-3,2), (-3,1), (-3,0)],
'goals':{(3,-3), (3,-2), (3,-1), (3,0)},
'score':0
}
self.green = {
'positions':[(0,-... |
"""
The main converter program. Handles the command-line arguments and starts the needed conversion depending on them.
"""
import argparse
def initialize_graphics():
""" Prints introduction graphics """
print "\n###################################################################"
print "### ... |
a = input()
if a.isupper():
print(a.lower())
elif a[0].islower() and a[1:].isupper():
print(a[0].upper() + a[1:].lower())
elif len(a) == 1:
print(a.upper())
else:
print(a)
|
a = input()
a = a.split(' ')
for i in range(0, len(a)):
if(a[i] == '-'):
pos = i
if pos == 0:
a[1] = a[1].split(':')
b = list(a[1])
print(b[1])
b = int(b[1])
|
class Student:
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade # 0 - 100
def get_grade(self):
return self.grade
class Course:
def __init__(self, name, max_students):
self.name = name
self.max_students = max_students... |
"""Problem 3 - Largest prime factor
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143?
http://projecteuler.net/problem=3
"""
from collections import Counter
from operator import itemgetter
def find_prime_factors(n, factors=None):
if factors is None:
... |
def weight_on_planets():
earthstri = input("What do you weigh on earth? ")
earth = float(earthstri)
mars = earth * 0.38
jupiter = earth * 2.34
print("\nOn Mars you would weigh %.2f pounds.\nOn Jupiter you would weigh %.2f pounds." % (mars, jupiter))
if __name__ == '__main__':
weight_on... |
import random
record = 0
players_guess = int(input('Choose a number(Between 0-5):\n'))
computers_guess = random.randrange(0, 6)
print('You guessed: {}'.format(players_guess))
print('The computer chose: {}'.format(computers_guess))
print()
if players_guess == computers_guess:
print('Good Job!')
pr... |
"""
Kata: The Hidden Words - Write a function that will take a number
between 100 and 999999 and return a string with the word.
The input is always a number, contains only the numbers in the key.
The output should be always a string with one word, all lowercase.
#1 Best Practices Solution by GiacomoSorbi
hidden=lamb... |
from random import randint
class BubbleSort:
def __init__(self, _array) :
self._array = _array
def sort(self ):
for i in range(len(self._array)):
isSorted = True
for j in range(1 , len(self._array) - i):
if (self._array[j] < self._array[j - 1 ]) :
self._array = self._swap(self._array , j , ... |
my_name = 'Alejadro Medina'
my_age = 21
my_height = 165 # centimeters
my_weight = 64 # kilograms
my_eyes = 'Brown'
my_teeth = 'White'
my_hair = 'Black'
print(f"let's print some stuff{my_age}")
print(f"Let's talk about {my_name}")
print(f"He's {my_height} centimeters tall")
print(f"He's {my_weight} kg heavy")
print(f"... |
def addition(a, b):
a = int(a)
b = int(b)
result = a + b
print(result)
def subtraction(a, b):
a = int(a)
b = int(b)
result = a - b
print(result)
def multiplication(a, b):
a = int(a)
b = int(b)
result = a * b
print(result)
def division(a, b):
a = int(a)
b = int(... |
# pay program using try and except so that your program handles non-numeric input gracefully by printing a message and exiting the program. The following shows two executions of the program:
hours = input('Enter Hours: ')
rate = input('Enter Rate: ')
try:
hours = float(hours)
rate = float(rate)
print('Both... |
def main():
my_string = input("What is the string of digits you would like to sum? ")
total = 0
for ch in my_string:
ch = int(ch)
total += ch
print("Your total is", total)
main() |
def main():
my_string = "Hello World, tttt"
my_string_upper = my_string.replace("t", "T")
print(my_string_upper)
main()
|
def main():
str = "StopAndSmellTheRoses"
index = 0
converted_string = ""
for ch in str:
if ch.isupper() and index != 0:
converted_string += " "
converted_string += ch
index += 1
cap_string = converted_string.capitalize()
print(cap_string)... |
"""
Напишите функцию update_dictionary(d, key, value), которая принимает на вход словарь
dd и два числа: keykey и valuevalue.
Если ключ keykey есть в словаре dd, то добавьте значение valuevalue в список,
который хранится по этому ключу.
Если ключа keykey нет в словаре, то нужно добавить значение в список по
ключу 2 * ... |
"""
Напишите программу, которая считывает с клавиатуры два числа a a a и b b b, считает и выводит
на консоль среднее арифметическое всех чисел из отрезка [a;b] [a; b] [a;b], которые кратны
числу 3 3 3.
В приведенном ниже примере среднее арифметическое считается для чисел на отрезке
[−5;12] [-5; 12] [−5;12]. Всего чисел... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.