text stringlengths 37 1.41M |
|---|
"""
print("hello word")
print(123)
print(None)
print(0.3)
print(True,False)
print(())
print({})
print([])
a = "哈哈哈哈哈" #把哈哈哈赋值给a这个变量
print(a)
name = "呼呼"
print("你好,{}".format(name))
print("你好,"+name)
print("1"+"1")
print((11-3)*31+88/22)#逻辑运算符
print(10%4)#求余
print(2>1)
#input()获取输入
name = input("请输入你的姓名:")
print("... |
for b in range(3,0,-1):
print("黄灯还有",b,"秒结束")
for b in range(35,0,-1):
print("绿灯还有",b,"秒结束")
for b in range(30,0,-1):
print("红灯还有",b,"秒结束")
username = input("账号")
password = input("密码")
if len(username) >=3 and len(username) <= 8:
print("username")
if username[0] in "zxcvbnmlkjhgfdsaqwertyu... |
# 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
N = len(A)+1
missing = N
for i in range(1, N):
missing ^= A[i-1]
missing ^= i
return missing
|
k = int(input("Enter the number of digits .... "))
print("Probablity P1 where P1 is that the k-digit number does NOT contain the digits 0 , 5 , 9 out of 10 integers from 0 to 9 is : ",(7/10)**k)
print("Probablity P2 where P2 is that the k-digit number does NOT contain the digits 0 , 5 , 9 out of { 0 , 1 , 3 , 4 , 5... |
import time
"""
x = 0
t0 = time.time()
for i in range(1000000):
x += 1
t = time.time() - t0
print("one million iterations in ", t, " seconds")
# real python3 is about 100x faster
"""
x = 0
t0 = time.time()
for i in range(1000000):
x = x+1
t = time.time() - t0
print("one million iterations in ", t, ... |
import abc
from abc import ABC
class IMath(ABC):
@abc.abstractmethod
def addition(self, num1, num2):
pass
@abc.abstractmethod
def substraction(self, num1, num2):
pass
@abc.abstractmethod
def multiplication(self, num1, num2):
pass
@abc.abstractmethod
def di... |
import abc
from abc import ABC
class AbstractCoffee(ABC):
@abc.abstractmethod
def get_cost(self):
pass
@abc.abstractmethod
def get_ingredients(self):
pass
def get_tax(self):
return 0.1*self.get_cost()
class ConcreteCoffee(AbstractCoffee):
def get_cost(self):
... |
#To create a single node in binary tree
#class
class Node:
def __init__(self,data):
self.left=None
self.right=None
self.data=data
#print
def PrintTree(self):
print(self.data)
tree=Node(25)
#calling print function
tree.PrintTree()
|
#Identify the biggest and smallest key in a doubly linked list containing integers.
#node class
class node:
#constructor
def __init__(self,data):
#instances
self.data = data
self.prev = None
self.next = None
#linkedlist class
class LinkedList:
def __init__(self):
#initialization
self.head = None
#print... |
#ascii password generator
#using python andaconda
#TO EXECUTE -> $pythonw ctfPass.py
#by joe hollon
import random
import time
#method 2 random number way(ascii)
#set up a random number generator that took the ascii values 65-122 randomly picked the range
count = 0
sum = 83
sumList = []
wor... |
"""
This is a logger module, to simplify logging to the screen.
Logs messages are printed in the following format:
LOG LEVEL : [ Timestamp ] : Message
Log levels include NONE, ERROR, WARNING, INFO and DEBUG.
No log messages above current verbose level will be printed.
"""
import sys
import datetime
class Logge... |
"""
Problem Statement:
We have a collection of stones, each stone has a positive integer weight.
Each turn, we choose the two heaviest stones and smash them together. Suppose the stones have weights x and y with x <= y.
The result of this smash is:
If x == y, both stones are totally destroyed;
If x != y, the stone o... |
"""
Problem Statement:
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically.
You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input:
11110
11010
11000
0... |
import string
# turn a doc into clean tokens
def clean_doc(doc):
# replace '--' with a space ' '
doc = doc.replace('--', ' ')
# split into tokens by white space
tokens = doc.split()
# remove punctuation from each token
table = str.maketrans('', '', string.punctuation)
tokens = [w.translate(table) for w in token... |
import sqlite3
import webbrowser
def search():
# database file connection
database = sqlite3.connect("Database")
# cursor objects are used to traverse, search, grab, etc. information from the database, similar to indices or pointers
cursor = database.cursor()
temp = input("Do you und... |
import sqlite3
# database file connection
database = sqlite3.connect("Database")
# cursor objects are used to traverse, search, grab, etc. information from the database, similar to indices or pointers
cursor = database.cursor()
def delete_instructor():
targetCRN = input("please enter the ID of the instructor you... |
class User:
# Base Class that all classes are built off of
def __init__(self, user_id="7", first_name="7", last_name="7", passcode="7"):
# This is the initialization function
# if no paramaters are passed into it, the default listed will be used
self.user_id = user_id # U... |
# multiple linear Regression
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('50_Startups.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 4].values
#Encoding categorical data
# Encoding categorical ... |
#pragati Vilas Kate
gr no.11810418
def max_of_two(x,y):
if x>y:
return x
return y
x=int(input())
y=int(input())
z=int(input())
a=max_of_two(z,max_of_two(x,y))
print(a)
|
import tkinter as tk
from tkinter import filedialog
from tkinter import *
from PIL import ImageTk, Image
def UploadAction(event=None):
filename = filedialog.askopenfilename()
#path2.insert(END, filename)
im = Image.open(filename)
im = im.resize((320, 320))
tkimage = ImageTk.PhotoImage(im)
my... |
# Pythonの型
## 数値型
"""
・整数(int)
・少数、実数(float)
・複素数
"""
i = 0
i += 1
print(i) # 1
"""
以下は同じ
i = i + 1
i += 1
"""
print(10 - 2) # 8
print(10 * 2) # 20
print(10 // 3) # 3
print(10 % 3) # 1
print(10 ** 3) # 1000
"""
/...小数点が返ってくる
//...切り捨て
"""
print(5 // 2) # 2
print(5 / 2) # 2.5
## 文字列
print('I love ' + 'Python') # ... |
# コメント
print("Hello world")
"""
コメント
"""
print(10)
print(10 + 5) # 足し算
print(10 - 5) # 引き算
print(10 * 5) # 掛け算
print(10 / 5) # 割り算
print(10 % 3) # 余り
print("10 + 5") # 文字列
print(10 + 5) # 数値
"""
変数とは、データを入れておく箱のようなもの
「変数名 = 値」で定義する。右辺を左辺に代入する
変数で使用できるのは、アルファベット、数字(先頭は不可)、「_」
"""
name = 'Tom'
age = 20
print(name) ... |
import math
from tkinter.constants import LEFT
from pickle import FALSE
#global
gIterations = 0
recursiveCount = 0
def NaiveCount(Max, Digit):
TotalCount = 0;
iterationCalc = 0
for x in range(0, int(n)+1,1):
num = x;
while (num > 0):
iterationCalc = iterationCalc + 1
... |
"""
Commenting skills:
TODO: above every line of code comment what you THINK the line below does.
TODO: execute that line and write what actually happened next to it.
See example for first print statement
"""
import platform
# I think this will print "hello! Let's get started" by calling the print function.
print("h... |
'''
1、简述变量命名规范
'''
# 变量命名规范
# 1.变量必须要要有数字,字母,下划线任意组成
# 2.变量需要具有可描述性
# 3.变量命名不能过长,不能以数字开头,不能包含中文,不能包含python关键字
# 4.推荐1,使用驼峰体:ZhangZheng = me
# 推荐2:使用下划线:my_name_ha = zz
'''
2.name = input(">>>") name变量是什么数据类型?
'''
# name = input(">>>")
# str转换为int
# name = int(name)
# print(name,type(name))
# input输入的数据类型在没有转换的情况下,都是是... |
'''
从“学生选课系统” 这几个字就可以看出来,我们最核心的功能其实只有 选课。
角色:
学生、管理员
功能:
登陆 : 管理员和学生都可以登陆,且登陆之后可以自动区分身份
选课 : 学生可以自由的为自己选择课程
创建用户 : 选课系统是面向本校学生的,因此所有的用户都应该由管理员完成
查看选课情况 :每个学生可以查看自己的选课情况,而管理员应该可以查看所有学生的信息
工作流程:
登陆 :用户输入用户名和密码
判断身份 :在登陆成果的时候应该可以直接判断出用户的身份 是学生还是管理员
学生用户 :对于学生用户来说,登陆之后有三个功能
1、查看所有课程... |
name =input("Enter file: ")
if len(name) < 1:
name = "mbox-short.txt"
fhand = open(name)
lst=list()
#create a list with hours of line start with From
for line in fhand:
if not line.startswith("From "):
continue
else:
x=line.split()
lst.append(x[5])
ls=list()
for y in lst:
y=... |
def add(x,y):
return x+y
for i in range(0,10):
d = add(i, i*2)
print(d) |
# Exercicio 11
from random import randrange
palavras = input("Digite as palavras: ")
palavras = palavras.split(" ")
uma_palavra = palavras[randrange(0, len(palavras))]
palavra_forca = ["_" for i in uma_palavra]
chance = 1
while chance < 7 and palavra_forca.count("_") != 0:
letra = input("Digite uma letra: ")
... |
#Stemming - stemming is a method of finding the roots of the words
# from the sentence For eg: written = write
from nltk.stem import PorterStemmer #importing the PortStemmer function
from nltk.tokenize import word_tokenize #importing the word_tokenize function
data = " A cemetery is a placing wher... |
from collections import defaultdict
class Graph:
def __init__(self, vertex, edge):
# self.vertex = set(vertex)
# frozenset - we want vertices to be unordered sets, we cannot have sets of sets, so it is sets of frozem sets
self.edge = set(frozenset((u, v)) for u, v in edge)
# defaul... |
games = []
while True:
menu = input("Val: ")
if menu == "1":
for l in games:
print(l)
elif menu == "2":
games ={}
games ["company"] = input ("Company: ")
games ["game"] = input ("Game: ")
games["year"] = int(input("Year"))
games.append(games... |
"""
Moduł zawierający wszyskie funkcje służące do komunikacji oraz modyfikacji z bazą danych aplikacji
"""
import sqlite3
from tkinter import messagebox
def check_login_is_free():
"""Funkcja zwracająca listę loginów uzytkowników aktualnie znajdującyhc się w bazie danych
@return (list)"""
conn = sqlit... |
import sys
import random
def return_score(roll):
local_score = 0
r_set = list(set(roll)) #set is all unique elements; list makes it indexable
cnt_all_rolls = [roll.count(i) for i in [1,2,3,4,5,6]]
# 3 DICE ********************************************************
# scoring ones and fives but no tr... |
def invertTree(self, root: TreeNode) -> TreeNode:
"""
Recursive
"""
if not root:
return
temp = root.left
root.left = root.right
root.right = temp
self.invertTree(root.left)
self.invertTree(root.right)
return root
... |
# Written by Eric Martin for COMP9021
# Draws three coloured dodecagrams, separed by a distance of
# one third the length of the edges, and centred in the window
# that displays them.
from turtle import *
edge_length = 150
angle = 150
def draw_dodecagram(colour):
color(colour)
begin_fill()
for _ in ... |
def get_points(mazeArray):
global wallsList
wallsList = []
for i in range(len(mazeArray)):
for j in range(len(mazeArray[i])):
current = []
current.append(j)
current.append(i)
if mazeArray[j][i] == "1":
wallsList.append(current)... |
import sqlite3
from sqlite3 import Error
def create_connection(db_file):
""" create a database connection to a SQLite database """
conn = None
try:
conn = sqlite3.connect(db_file)
print(sqlite3.version)
except Error as e:
print(e)
return conn
def create_table(conn, create_... |
#!/usr/bin/env python3
# Created by: Ben Whitten
# Created on: November 2019
# This is a program which finds the volume of the cylinder.
import math
# This allows me to do things with the text.
class color:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\0... |
import math
import tkinter as tk
import keyboard
import os
import sys
window = tk.Tk()
window.overrideredirect(1)
window.state('zoomed')
textFont = ("Arial Bold", 15)
window.geometry("200x200")
window.title("Project_08")
def button1Clicked():
try:
if editText2.get() == "pi":
... |
a = input()
b = input()
c = input()
n1 = float(1)
n2 = float(1)
n3 = float(1)
a = float(a)
b = float(b)
c = float(c)
if a >= b and a >= c:
n1 = a
if b >= c:
n2 = b
n3 = c
else:
n2 = c
n3 = b
if b >= a and b >= c:
n1 = b
if a >= c:
n2 = a
n3 = c
el... |
#Question No: 3
def even(n):
for i in range(2, n):
if i%2 == 0 or i%3 == 0:
print(i, end=', ')
even(36) |
import os
import csv
#import datetime to deal with dates column
from datetime import datetime
#Path to the budget_data.csv file.
PyBankCSV = os.path.join("Resources","budget_data.csv")
#create lists to store the two columns of CSV data
dates = []
profit_loss = []
#set total profit to 0 to start
totalprofit = 0
#se... |
from random import randint
def mergesort(arr):
if len(arr) > 1:
half = int(len(arr)/2)
arr1 = arr[0:half]
arr2 = arr[half:len(arr)]
return merge(mergesort(arr1), mergesort(arr2))
else:
return arr
def merge(arr1, arr2):
if (arr2 is None):
... |
# Source : https://leetcode.com/problems/two-sum/
# Author : Yudistira Virgus
# Date : 2015-04-04
#
# *****************************************************************************************************************************
# Problem 1
# Title : Two Sum
# Difficulty : Medium
# Problem statement :
#
# Given an a... |
#Begin Game - Welcome message - Version 2.0 from October 21st
print('**--** Welcome to the Tic-Tac-Toe challenge game! **--**')
# Import modules
import random
# Generates a random number between
# a given positive range
r1 = random.randint(0, 10)
opprand = input("Opposing Human, please enter a number between 0-10... |
"""
Practica 3:Dada la siguiente llamada a una función anónima:
suma(10,11)
Desarrollar la función; debe presentar en pantalla para el ejemplo 21
autor: Roberto N
"""
suma = (10,11)
# Funcion lambda para sumar cifras
mifuncion = lambda x: x[0] + x[1]
# Salida de datos
print(mifuncion(suma)) |
import turtle
import time
import random
posponer = 0.15
# Escenario del juego
window = turtle.Screen()
window.title("Snake Game @BrayanAltamar")
window.bgcolor("black")
window.setup(width=600,height=600)
# Cabeza Serpiente
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("green")
head.penup()
hea... |
def strStr(haystack, needle):
return len(haystack.split(needle)[0]) if needle in haystack else -1
print(strStr("hello",'ll')) |
def count_words(text):
text = text.replace(',','').replace(',','').replace('.','').replace('!','').replace('?','').lower().split()
wordCount ={}
i= 0
temp =''
for word in text:
if word in wordCount:
wordCount[word]+=1
else:
wordCount.update({word:1})
finalString=""
for x,y in w... |
def sentiment_scores(sentiments, texts):
sentiment_list =[]
for text in texts:
feeling = 0
text_list = text.replace("!","").replace(".","").replace(",","").split()
for word in text_list:
if word in sentiments:
feeling +=sentiments[word]
sentiment_list.append(feeling)
... |
def find_index(sorted_list, target):
low, high = 0, len(sorted_list)-1
n =len(sorted_list)-1
while low <=high:
if sorted_list[low] >= target:
return low
if sorted_list[high] == target or (high-low == 1):
return high
if sorted_list[high]<target:
return high+1
mid = (low+hi... |
def last_factorial_digit(n):
x = 1
for i in range(n,0,-1):
x*=i
return(x%10)
if __name__ == "__main__":
print(last_factorial_digit(int(input()))) |
class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
class Tree:
def __init__(self):
self.root = None
def print_bfs(self):
if not self.root:
return
queue = [self.root]
while len(queue) > 0:
current_node = queue.pop(0)
print(cur... |
def merge_sort(nums):
if len(nums)>1:
mid = len(nums)//2
right = nums[0:mid]
left = nums[mid:]
right = merge_sort(right)
left = merge_sort(left)
sorted_list = []
while len(right) > 0 and len(left)>0:
if right[0]>left[0]:
sorted_list.append(left.pop(0))
... |
def bubble_sort_swaps(nums):
swapped = True
count=0
while swapped:
swapped=False
for i in range(len(nums)-1):
if nums[i]>nums[i+1]:
nums[i], nums[i+1] = nums[i+1], nums[i]
swapped=True
count+=1
return count
print(bubble_sort_swaps([6,2,4,3])) |
## Given this recursive solution to the longestPalindrome problem,
## Start by writing out the recursive tree of function calls to understand the problem
## then, think about how you might turn this into an iterative solution.
def longestPalindrome(s):
n = len(s)
table = [[0 for x in range(n)] for y in range(n)]... |
def prime(num):
isprime = True
for i in range(2, num-1):
if num%i == 0:
isprime = False
if isprime:
return True
else:
return False
while True:
a = int(input("enter a number..."))
if prime(a):
print("hey the number is prime dude!!")
break
else:
print("sorry retry... :(") |
# -*- coding: utf-8 -*-
# Project: maxent-ml
# Author: chaoxu create this file
# Time: 2018/2/27
# Company : Maxent
# Email: chao.xu@maxent-inc.com
"""
this funtion used to solve 8 queens problems
"""
def chk_pos(queen_state, next_pos):
"""
:param state:
:param next_pos:
:return:
"""
for i, j... |
#Displaying patterns
n=int(input("Enter n:"))
def display(n):
for i in range (n):
A=[]
for j in range (n):
if j<=i:
A.append(j+1)
else:
if 10<=j+1<100:
A.append(' ')
elif 100<=j+1<1000:
... |
'''
This abstract class defines an interface that has to be used in order to be
compliant with the PropertiesTable handled objects
'''
import abc
class PropertiesTableAbstract( object ):
__metaclass__ = abc.ABCMeta
'''
usually an implementation like this is used
self.sanitizeProperties()
... |
"""
Class used to run singular tests for specific features.
"""
import importlib
import inspect
import os
testPath = "src/tests/"
class Tests():
def __init__(self):
self.modules = {} # dict of modules containing tests
def autoImport(self):
"""
Automatically import all tests in src/te... |
'''
ONCE class:
Simple structure that if checked with get() method, return true on first check,
false all the others.
'''
class Once:
#constructor
def __init__(self):
self.value = True
def get(self):
if self.value == True:
self.value = False
return True
... |
### Email Validation ###
########################
# input:
# Masukkan alamat Email:
# Kondisi:
# - Memiliki format: nama user@nama hosting.ekstensi
# - Nama user hanya boleh: huruf, angka dan underscore dan titik
# - Nama hosting hanya boleh: huruf dan angka
# - nama ekstensi hanya boleh huruf dan maksimal 5 karakt... |
import random
def merge(A, start, end):
start = int(start)
end = int(end)
L = A[start:(start + end)/2+1]
R = A[(start + end)/2 + 1:(end+1)]
L.append(10**9)
R.append(10**9)
i = 0
j = 0
for k in range(start, end + 1):
if L[i] > R[j]:
A[k] = R[j]
j = j + 1
elif L[i] < R[j]:
A[k] = L[i]
i = i + 1
... |
'''
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。
例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。
但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
'''
# -*- coding:utf-8 -*-
class Solution:
def movingCount(self, k, rows, cols):
#首先建立布尔数组,检测格点是否之前已经记录过
visite... |
'''
输入一个英文句子, 翻转句子中单词的顺序,但单词内字符的顺序不变
为简单起见, 标点符号和普通字母一样处理
'''
#fangfa一 ,利用python的方法
class Solution:
def ReverseSentence(self, s):
if s == None or len(s)<=0:
return ''
l = s.split(' ') #字符串句子按照空格进行切割
return ' '.join(l[::-1])
#方法二 一个个字母的处理方式
'''
这个思路很简单的,从前往后一直读取,遇... |
'''
随机从扑克牌中抽出了5张牌,判断是不是顺子,
决定大\小 王可以看成任何数字,并且A看作1,J为11,Q为12,K为13。
'''
'''
剑指思路:1排序 2. 统计数组中0的个数 3. 统计排序数组中相邻数字之间的空缺总数
如果2》=3那么就是顺子 如果有顺子那么就肯定不是顺子
'''
class Solution:
def IsContinuous(self,numbers):
if numbers == None or len(numbers)!=5:
return False
numbers = sort... |
'''
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。
由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
'''
'''
解法二根据数组特点找出o(n)算法
保存两个数一个是数组中的一个数组数字。如果下一个数字和当前保存的数字相同,次数加1
不同 次数减1 。。
要找的数字的肯定是最后一次把次数设为1时对应的数字
'''
# -*- coding:utf-8 -*-
class Solution:
def MoreThanHalfNum_Solution(self... |
class Point(object):
def __init__(self, x=0., y=0.):
self.x = x
self.y = y
def __iadd__(self, other):
if isinstance(other, Point):
self.x += other.x
self.y += other.y
return self
def __add__(self, other):
if isinstance(other, Point):
... |
# -- coding: utf-8 --
import dataStru as ds
def find(inputs, target):
"""
1. 二维数组中的查找
"""
if inputs == None or len(inputs) <= 0: return False;
M = len(inputs) #row
N = len(inputs[0]) #col
i = M - 1
j = 0
while(i >= 0 and j < N):
if target == inputs[j][i]:
... |
# Your code here
def finder(files, queries):
"""
YOUR CODE HERE
"""
# Your code here
files_table = []
words_table = {}
for word in files:
# split path by /
path = word.split("/")
# target last item
name = path[-1]
# checks if last item is in... |
#!/usr/bin/python
# David Newell
# GeoUtils/functions.py
# Geographical Utilities package functions
def makeBoundingPolygon(north=90,south=-90,east=180,west=-180):
"""
Function to create a MySQL bounding rectangular polygon based on four edge points
Inputs:
north, south, east, west - latitude... |
### search takes as input a search queue, a path factory, a function that
### returns true if the state provided as input is the goal, and the maximum
### depth to search in the search tree.
### Should print out the solution and the number of nodes enqueued, dequeued,
### and expanded.
def search(queue, initialStat... |
name = input('ENTER NAME ')
print ('Hello My Name is, '+ name)
if name == 'Eli':
print ('hey eli')
ave = input('Eli what is your old Ave? ')
if ave == '8':
print ('Thats right!')
if ave == '9':
print ('Thats wrong!') |
def cari_sama(my_list,elemen):
backup_list=[]
mark = False
for i in range(len(my_list)):
if elemen == my_list[i]:
mark = True
backup_list.append(i)
if mark == True:
print("list ini memiliki data yang sama dengan elemen yang anda ketik pada index")... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 12 13:54:20 2018
@author: Hesam
"""
def domain_name(url):
start = url.find(":")
url = url[start+1:]
dots = url.count(".")
if dots == 2:
ind1 = url.index(".")
url = url[ind1+1:]
ind2 = url.index(".")
return ur... |
#Traveling salesman problem solved using Simulated Annealing.
import time
from scipy import *
from pylab import *
start_time = time.time()
def Distance(R1, R2):
return sqrt((R1[0] - R2[0]) ** 2 + (R1[1] - R2[1]) ** 2)
def TotalDistance(city, R):
dist = 0
for i in range(len(city) - 1):
... |
a = int(input('введите а: '))
b = int(input('введите b: '))
c = int(input('введите c: '))
def two_of_three(a, b, c):
num1 = max(a, b)
num2 = max(b, c)
print('1 max значение', num1)
print('1 max значение', num2)
return num1 + num2
print('итого результат', two_of_three(a, b, c)) |
print("Leer un número entero de tres dígitos y mostrar todos los enteros comprendidos entre 1 y cada uno de los dígitos")
numero = input("Ingrese un numero entero de tres digitos: ")
lista = list(map(int,numero))
dig1 = lista[0]
dig2 = lista[1]
dig3 = lista[2]
todos1 = 0
todos2 = 0
todos3 = 0
print("Los en... |
print("Generar los números del 1 al 10 utilizando un ciclo que vaya de 10 a 1")
for ciclo in range (10, 0, -1):
print(ciclo)
input("Fin")
|
print("Leer un número entero de 3 dígitos y determinar si tiene el dígito 1")
numero = input("Ingresar un numero entero de tres digitos: ")
lista = list(map(int,numero))
dig1 = lista[0]
dig2 = lista[1]
dig3 = lista[2]
if (dig1 == 1) or (dig2 == 1) or (dig3 ==1):
print("El numero tiene el digito 1.")
e... |
#Imprimir numeros impares
print(" Numeros Impares")
for i in range(1,5000):
if( (i % 2)== 1):
print(i)
|
print("Leer un número entero y mostrar en pantalla su tabla de multiplicar")
numero = int(input("Ingrese un numero entero: "))
for mult in range (1,13):
producto = numero * mult
print(numero,"*",mult," = ",producto)
input("Fin")
|
class A():
def __init__(self, color, size):
self.color = color
self. size = size
def __str__(self):
return f"color = {self.color} size = {self.size} "
class B():
def __init__(self, aa):
self.aa = aa
def __str__(self):
return f"aa = {self.aa}"
a = A("green",15)... |
import csv
with open('numbers.csv') as csvDataFile:
csvReader = csv.reader(csvDataFile)
for row in csvReader:
print("\n", row[0])
creditcard = row[0]
Reverse = 0
while(int(creditcard) > 0):
Reminder = int(creditcard) % 10
Reverse = (Reverse * 10) + Remi... |
#!/usr/bin/env python
"""Convert intersections to coordinates
Requires a Google API key (in quotes) in google_secret.json.
Get a key from
https://console.developers.google.com/flows/enableapi?apiid=geocoding_backend&keyType=SERVER_SIDE&reusekey=true
"""
import json
import requests
def geocode(road1, road2):
"""... |
#string and variable manipulation
parrot = "African Grey Parrot"
print(parrot)
#prints the string, duh
print(parrot[0])
#prints the first letter in string, A
print(parrot[-1])
#prints last letter, t
print(parrot[0:6])
#prints the range from 0 index to 6 index, prints Africa
print(parrot[6:])
#prints n Grey Parrot
... |
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(list)
print(type(list))
print(list[2])
print(list[0:5])
# this prints [1, 2, 3, 4, 5] but not 6, which is the 5th index
# doesn't print the last item in the list
# Python slices only gives up to and not included that index
range(0, 10)
for i in range(0, 10):
print(i, en... |
#!/usr/bin/python3
# modules.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
import sys
# sys is for specific parameters and functions
# module provides access to some variables used or maintained by the interpreter and to functions that interact
# strongly... |
# iterating through values
# using the for loop to iterate through a list, you can use it everytime you want to iterate through a list
filelist = [2015, 2017, 2019]
for item in filelist:
print(item)
# prints each item in the list
for item in range(2015, 2030, 2):
print(item)
# prints every other item in range, ... |
# returning values from functions
#!/usr/bin/python3
# functions.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
def main():
for n in testfunc():
print(n, end=' ')
# print(testfunc())
def testfunc():
# return 'This is a test function'
... |
a = 12
b = 3
print(a + b)
print(a - b)
print(a * b)
print(a / b)
# in python, the division operation returns as a float, 4.0
print(a // b)
# this returns an integer
print(a % b)
#modulo returns the remainder
for i in range(1, a/b):
print(i)
#produces an error, the range needs a whole number, not a float
#in place op... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
u"""primes.py
Helper function to calculate prime numbers.
Created by Freek Dijkstra on 2008-11-06. Contributed to the public domain, so far as possible (most of the code is inspired by others).
"""
import math
import itertools
import sys
def fastprimes(max = None):
"... |
'''A3. Tester for the function common_words in tweets.
'''
import unittest
import tweets
class TestCommonWords(unittest.TestCase):
'''Tester for the function common_words in tweets.
'''
def test_empty(self):
'''Empty dictionary.'''
arg1 = {}
arg2 = 1
exp_arg1 = {}
... |
import sys
import csv
import operator
#1. Which Region have the most State Universities?
def get_region_with_most_suc():
with open('suc_ph.csv', 'rb') as f:
# f = open('suc_ph.csv', 'r')
suc = {}
for index, line in enumerate (f):
row = line.split(',')
if row[0] in suc:
suc [row[0]] += 1
... |
import random
import prompt
import operator
def calc_gen(name):
print('What is the result of expression?')
for _ in [1, 2, 3]:
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
operations = {'+': operator.add,
'-': operator.sub,
'*': ... |
#!/usr/bin/env python3
"Python engine for practicing simple math."
from __future__ import print_function # To shut PyLint up
import random
class Engine(object): # pylint: disable=too-few-public-methods
"Main engine class."
def __init__(self, database=None):
self.database = database
def start(se... |
"""
На площині ХОY задана своїми координатами точка А (координати ввести з клавіатури). Вказати, де вона розташована (на якій осі або в якому координатном куті).
"""
import re
re_float = re.compile("^[-+]{0,1}\d+\.{0,1}\d*$")
def validator(pattern, promt):
text = input(promt)
while not bool(pattern.match(tex... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 1 23:17:33 2019
@author: ILYAS
"""
import random
def bridge_of_death(text):
print('KEEPER: STOP!' + text)
finish = False
while finish == False:
name = input('KEEPER: What is ' + questions[0] + ' ')
if not name.upper() in answers[0... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.