text stringlengths 37 1.41M |
|---|
#operations
#len()
string="I am writing python script"
name_lst=['justin','davies','clark','tries','manual']
num_lst=[10,3,4,6,7,8]
print "-------------------------------------------"
print string
print name_lst
print num_lst
print "Length of the string is ->",len(string)
print "Length id the List->",len(... |
"""
1. Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.
Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль.
"""
def ask_float(prompt):
while True:
s = input(prompt)
try:
return float(s)
except ValueErr... |
"""
1. Создать список и заполнить его элементами различных типов данных.
Реализовать скрипт проверки типа данных каждого элемента.
Использовать функцию type() для проверки типа.
Элементы списка можно не запрашивать у пользователя, а указать явно, в программе.
"""
items = [None, 1, 2.2, 'boo', True, (1, 2), [3, 4], {5,... |
"""
Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами.
Программа должна подсчитывать сумму чисел в файле и выводить ее на экран.
"""
import random
def int_seq_file(file_name, seq_len, min_int=1, max_int=1000):
with open(file_name, 'w', encoding='utf-8') as file:
... |
"""
Реализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина).
Значения данных атрибутов должны передаваться при создании экземпляра класса.
Атрибуты сделать защищенными.
Определить метод расчета массы асфальта, необходимого для покрытия всего дорожного полотна.
Использовать формулу... |
hello = "hello python" #string array: 0~len() -1
print(hello[1:3]) #index 1 ~ (3-1)
print(len(hello)) #length
print("'hello python' length is {0}".format(len(hello))) #string format
print(hello.upper())
print(hello.lower())
print("{0} is alphabet?".format(hello.isalnum()))
print("'1'문자열 검색 ", hel... |
def multiply(x):
return 5*x
x = int(input('enter a number'))
y = multiply(x)
print(y)
|
t=int(input())
n=int(input())
s=input()
# Alphabets from a to p are encoded using 4 bit binary digits. The program aims at decoding the encoded key to retrieve the hidden message.
reference = {
key: val for key, val in zip(
[bin(num).replace('0b', '').rjust(4, '0') for num in range(16)],
'abcdefg... |
# Coin Piles
def solution(a: int, b: int) -> bool:
return (
(2 * a - b) % 3 == 0
and (2 * b - a) % 3 == 0
and (2 * a - b) >= 0
and (2 * b - a) >= 0
)
def main():
t = int(input())
result = []
for _ in range(t):
a, b = map(int, input().split())
resul... |
import re
def is_funny(s):
s = [ord(val) for val in list(s)]
r = s[:]
r.reverse()
n = len(s)
i = 0
while i < n - 1:
if abs(s[i + 1] - s[i]) != abs(r[i + 1] - r[i]):
break
i += 1
return i == n - 1
def main():
t = int(raw_input())
for ti in xrange(t):
s = raw_input()
print('Funny' if is_funny(s) els... |
import re
def binary_search(a, key):
ll = 0
rr = len(a) - 1
while ll <= rr:
mm = (ll + rr) / 2
if key > a[mm]:
ll = mm + 1
elif key < a[mm]:
rr = mm - 1
else:
return mm
return -1
def main():
key = int(raw_input())
n = int(raw_input())
a = [int(val) for val in re.split(' ', raw_input())]
print... |
from Algorithm import Algorithm
class IDS(Algorithm):
"""
the class solves different problems by running IDS algorithm
"""
def run(self, init_state, goal_state, max_depth):
"""
run IDS algorithm on a given problem
:param init_state: the initial state of the problem
... |
def comparelists(list1,list2):
list3 = []; list4 = [];
for each in xrange(len(list1)):
if list1[each] != list2[each]
list3.append(list1[each])
list4.append(list2[each])
print list1
print list2 |
def bubble_sort(List1):
i=0
while i<len(List1):
j=i+1
while j<len(List1):
if List1[i]<List1[j]:
List1[i],List1[j]=List1[j],List1[i]
j=j+1
i=i+1
print(List1)
(bubble_sort(List1=[7,8,3,4,10])) |
#!/usr/bin/env python3
def is_valid(pw):
pw = str(pw)
d1 = pw[0]
invalid_repeat = None
locked_in_repeat = False
found_repeat = False
for d2 in pw[1:]:
if d2 < d1:
return False
elif not found_repeat and d2 == d1 and d2 != invalid_repeat:
found_repeat = Tru... |
# coding=utf-8
print('\n')
print('**********输出最小值************* \n')
number_1 = int(input("输入第一个数"))
number_2 = int(input("输入第二个数"))
number_3 = int(input("输入第三个数"))
min_number = 0
if number_1 < number_2:
min_number = number_1
if min_number < number_3 :
print("最小值是:", min_number)
else:
print("最小值是:",number_... |
# -*- coding: utf-8 -*-
# @Time : 2018/11/6 0006 20:04
# @Author : 北极的大企鹅!!
# @FileName: 008_list_other_4.py
# @Software: PyCharm
print('\n')
print('**********购物车编写 数组方式输出************* \n')
product_list = [
('Mac', 9000),
('Kindle', 800),
('Tesla', 900000),
('python book', 105),
('bike', 2000),
]
salary ... |
# coding=utf-8
print('\n')
print('**********while循环按照输入输出图形************* \n')
width =int(input("请输入长度值:"))
height =int(input("请输入宽度值:"))
height_num = 1
while height_num <= height:
width_num = 1
while width_num <= width:
print("#",end="\t")
width_num += 1
print()
height_num += 1
|
import chess
# Probably make this a class
#Very slow, should add Alpha beta pruning
board = chess.Board()
values = {
"K": 1000,
"Q": 90,
"R": 50,
"B": 30,
"N": 30,
"P": 10
}
"""
Ways to improve evaluation function:
Make mobility better in relation to each individual piece,
also change curren... |
'''Simple web api call to get city lattitude and longitude using googleapis'''
import urllib.request
import json
city='newyork'
url = 'http://maps.googleapis.com/maps/api/geocode/json?address='+city+'&sensor=false'
data_in_json = urllib.request.urlopen(url)
data = json.loads((data_in_json.read()).decode('utf-8'))
... |
from tkinter import*
from tkinter import ttk
from typing import Sized
import mysql.connector
from tkinter import messagebox #for showing a message after successfully adding a record in the database
import datetime #for due date and fine related stuff in book info
class lms:
def __init__(self,root):
... |
#Programa para calcular o Valor do salário após um aumento
salario = float(input('Digite o salário inicial: '))
porcento = float(input('Digite a porcentagem de aumento: '))
novosalario = salario+salario*(porcento/100)
print('O novo salário será',novosalario,'reais')
|
# Count decrements to nearest smaller element required to make all array elements equal
# Input: arr[] = {2, 5, 4, 3, 5, 4}
# Output: 11
# Explanation:
# Step 1: Replace all 5s with 4s. Therefore, arr[] = {2, 4, 4, 3, 4, 4}. Count of operations = 2
# Step 2: Replace all 4s with 3s. Therefore, arr[] = {2, 3, 3, 3, ... |
# Print Matrix after multiplying Matrix elements N times
#
# Input: mat[][] = {{1, 2, 3}, {3, 4, 5}, {6, 7, 9}}, N = 2
# Output:
# 25 31 40
# 45 57 74
# 81 103 134
#
# Input: mat[][] = {{1, 2}, {3, 4}}, N = 3
# Output:
# 37 54
# 81 118
# Python3 program for the above approach
# Function for matrix mu... |
# Minimum jumps required to make a group of persons sit together
#
# Given a string S of length N consisting of ‘x’ and ‘.’. The given string represents a row of seats where ‘x’ and ‘.’ represent occupied and unoccupied seats respectively. The task is to minimize the total number of hops or jumps to make all the occu... |
# Length of the longest substring with every character appearing even number of times
#
# Input: S = “324425”
# Output: 4
# Explanation: Two substrings consisting of even frequent elements only are “44” and “2442”. Since “2442” is the longer of the two, print 4 as the required answer.
#
# Input: S = “223015150”
... |
# Count unique paths with given sum in an N-ary Tree
# Given an integer X and integer N, the task is to find the number of unique paths starting from the root in N - ary tree
# such that the sum of all these paths is equal to X.The N - ary tree satisfies the following conditions:
# All the nodes have N children and ... |
Given an array A[] consisting of N integers, the task is to check if the sum of numbers of digits in each array element is a prime number or not.
# Python3 program for the above approach
import math
# Function to check whether
# a number is prime or not
def isPrime(n):
# Corner cases
if (n <= 1):
... |
# Count pairs whose product contains single distinct prime factor
# Input: arr[] = {1, 2, 3, 4}
# Output: 4
# Explanation:
# Pairs having single distinct prime factor in their product is as follows:
# arr[0] * arr[1] = (1 * 2) = 2. Therefore, the single distinct prime factor is 2.
# arr[0] * arr[2] = (1 * 3) = 3.... |
# Smallest number greater than or equal to N having sum of digits not exceeding S
# Given integer N and integer S, the task is to find the smallest number greater than or equal to N such that the sum of its digits does not exceed S.
#
# Input: N = 3, S = 2
# Output: 10
# Explanation: Sum of digits of 10 is 1, whic... |
# combine source code and test cases in a single file
# This can be directly run in coder pad
import unittest
from math import pi
def circle_area(r):
if r < 0:
raise ValueError("value is negative")
if type(r) not in [int, float]:
raise TypeError("not integer or type")
return pi * r ** 2
c... |
def f(g):
return g(2)
print(f(lambda x: x * x)) # 4
# It can't work in python, but in LISP it will return 2 because is interpreted as f(f(2))
print(f(f)) # error |
while True:
print("Write a sentence in lowercase and see it printed letter by letter! by Rohan Arni. Read readme.txt to see how to exit the program.")
linput=input("Enter a sentence here:")
morse_code_dict_key_find = list(linput)
morse_code_dict = {'a':'.-', 'b':'-...', 'c':'-.-.', 'd':'-..', 'e':'.', '... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 1 04:08:26 2018
@author: tuheenahmmed
while bal isnt close enough to zero:
do your 12 month calculation for latest payment value
if higher
elif lower
no else so it will be tested and ok at top of loop
Hopefully this isn't spoi... |
import urllib.request
import PyPDF2
import tempfile
import re
import pandas as pd
import sqlite3
from sqlite3 import Error
#df= pd.DataFrame(columns=['incident_time','incident_number','incident_location','nature','incident_ori'])
#getting the pdf file from the page which is provided as URL
def fetchIncidents(url):
... |
from Stack import *
def parentheses(str):
stack = Stack(len(str))
for i in str:
if i in "([{":
stack.push(i)
else: # )]}
top = stack.pop()
if not pair(top, i): #does the last item added to stack match(type of parenthese) current item
ret... |
from timeit import *
#recursive
def nthFibonacci(n):
if n == 0 or n == 1:
return n
else:
return nthFibonacci(n-1) + nthFibonacci(n-2)
#memoization
def nthFibonacci_(n, memo ={0:0,1:1}):
if n not in memo:
memo[n] = nthFibonacci_(n-1) + nthFibonacci_(n-2) #compute recursively if val not already saved... |
import random
import time
start = time.time()
data_list = random.sample(range(100), 50)
print(data_list)
'''
삽입정렬 로직
핵심: 1) 비교후 작은 값을 임시저장
2) 저장 후 앞에 있는 값과 비교 작은 값의 순서를 저장
3) 순서가 저장된 위치로 임시저장값을 삽입
'''
def insert_sort(data):
for i in range(0, len(data)-1, 1):
if (data[i] > data[i+1]):
... |
## 계좌 관리 class 작성하기
## - attribute: 계좌 초기 금액을 속성으로 하나 설정
## - 생성자에서 초기 금액은 0으로 설정
## - 속성은 private 으로 설정
## - method: 인출, 저축, 잔액 확인 세 가지 method 구현, 각각 현재 계좌 금액 리턴
class AccountMangement:
def __init__(self):
self.__balance = 0
def withdraw(self, amount):
if amount > self.__balance:
... |
# Write a function called rotate_word() that takes a string and an integer as parameters, and that
# returns a new string that contains the letters from the original string "rotated" by the given amount.
# For example, "cheer" rotated by 7 is "jolly" and "melon" rotated by -10 is "cubed".
# You might want to use the bu... |
str1 = 'accd'
str2 = 'acdd'
count = 0
if (len(str1) == len(str2)):
for i in range(0,len(str1)):
if str1[i] in str2 and str2[i] in str1:
count = count + 1
if count == len(str1):
print("anagram")
else:
print("Not") |
# class Student:
# age=21
# def student_report():
# print("Yes")
# s = Student()
# s.student_report()
# # Student.student_report()
# def A():
# a=12
# def B():
# b= a + 1
# print(b)
# A()
# B()
class Student:
def __init__(self,name):
self.name = name
def display(self):
... |
# Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters.
# Suppose the following input is supplied to the program:
# Hello world! Then, the output should be: UPPER CASE 1 LOWER CASE 9
string = "Hello world!"
upper = 0
lower = 0
for i in string:
if i.isalpha(... |
# 8: Display the phone number as below and also print the last 4 digit in ascending order
# input : 9993452133
# output :xxx-xxx-xxxx
phoneNo = input("Enter a phone no")
if len(phoneNo) == 10:
str1 = ''.join(sorted(phoneNo[-1:-5:-1])).strip()
print("XXX-XXX-", str1)
|
# 9: "There are 26 alphabets in English out of which 5 are vowels and 21 are consonants"
# Count the sum of numbers in the above statement using regular expression
import re
string = "There are 26 alphabets in English out of which 5 are vowels and 21 are consonants"
str1 = re.findall('[0-9]+',string)
sum = 0
for i in s... |
class vehicle:
def type(self):
print("Vehicle")
class four_wheeler(vehicle):
def type(self):
super().type()
print("four_wheeler")
class three_wheeler(vehicle):
def type(self):
super().type()
print("three_wheeler")
class car(four_wheeler):
def type(self):
... |
# Write a Python program to perform sum of three given integers. However, if any of the two values are equal then sum
# will be zero (eg : 2+1+1 = 0)
no1 = int(input("Enter a number"))
no2 = int(input("Enter a number"))
no3 = int(input("Enter a number"))
sum = 0
if no1 == no2 or no2 == no3 or no3 == no1 :
sum = 0
... |
# Modify your program to prompt the user to enter a string of forbidden letters and then print the
# number of words that don’t contain any of them. Can you find a combination of 5 forbidden letters
# that excludes the smallest number of words?
string = [input("Enter a string") for i in range(0, 5)]
forbidden_string ... |
# 2. Define a class Person and its two child classes: Male and Female.
# All classes have a method "getGender" which can print "Male" for Male class and "Female" for Female class.
class Person:
def getGender(self):
print("Gender is ",end='')
class Male(Person):
def __init__(self, gender):
se... |
string = input("enter a string")
dict1 = {}
for i in string:
dict1.update({i: string.count(i)})
print("dictionary : ", dict1)
dict1.pop('c')
print("dictionary : ", dict1)
dict1.popitem()
print("dictionary : ", dict1) |
num1 = int(input("enter a number"))
num2 = int(input("enter a number"))
list1 = [i for i in range(num1, num2) for j in range(2, i) if i != j and i % j == 0]
list2 = [j for j in range(num1, num2) if j not in list1]
print(list2) |
# 1:For the below binary number , count the Occurrence of sequence '101'
# 10101010100111101
import re
string = "10101010100111101"
count = 0
# str1 = re.findall('[1][0][1]',string)
for i in range(len(string)):
if i != len(string)-1 and i != len(string)-2:
if string[i] == '1' and string[i+1] == '0' and stri... |
# how to remove the duplicate character from String
string = input("Enter a String")
list1 = []
for i in string:
list1.append(i)
for i in list1:
if list1.count(i) > 1:
list1.remove(i)
str1 = ''
for i in range(0,len(list1)):
str1 = str1 + list1[i]
print(str1)
|
"""4.Read the IP Addresses from the file using regular expression """
import re
read_file = open("ip_address.txt", "r")
file_data = read_file.read()
regex_result = re.findall('[0-2][0-9][0-9]\.[0-2][0-9][0-9]\.[0-2][0-9][0-9]\.[0-2][0-9][0-9]',file_data)
print(regex_result)
read_file.close()
|
import Calculator
number1 = int(input("Enter a number"))
number2 = int(input("Enter a number"))
add_result = Calculator.addition(number1,number2)
sub_result = Calculator.subtraction(number1,number2)
print("Addition : ",add_result)
print("Addition : ",sub_result) |
#To test if the given letter is a vowel or a consonant.
def test_vowel(x):
if (x=='a' or x=='A' or x=='E' or x=='e' or
x=='i' or x=='I' or x=='o' or x=='O' or x=='u' or x=='U' ):
return True
else:
return False
|
"""
=== Module Description ===
This module contains the basic tree interface required by the treemap
visualiser. You will both add to the abstract class, and complete a
concrete implementation of a subclass to represent files and folders on your
computer's file system.
"""
import os
from random import randint
import ma... |
import string
## 1. write tests in lab03_tests.py
## 2. then code for the following functions
## Raising errors is more common when developing ------------------------
## These functions all take a single string as an argument.
## Presumably your code won't work for an int
## raise a built-in (or custom!) exception i... |
#coding=utf-8
import logging
import time
from multiprocessing import Pool
logging.basicConfig(level=logging.INFO, filename='logger.log')
class Point:
def __init__(self, x = 0, y= 0):
self.x = x
self.y = y
def __str__(self):
return "(%d, %d)" % (self.x, self.y)
def fun1(point):
point.x = point.x + 3
... |
"""
Your chance to explore Loops and Turtles!
Authors: David Mutchler, Dave Fisher, Valerie Galluzzi, Amanda Stouder,
their colleagues and Mariah Mufich.
"""
###############################################################################
# DONE: 1.
# On Line 5 above, replace PUT_YOUR_NAME_HERE with your o... |
"""
MODULE : basic_blocks
Purpose : * Class used to represent a basic block. Will be an array of instructions.
* All required algorithms such as register allocation etc. will be a part of this
class
Import Acronym : BB
"""
# List of Imports Begin
import debug as DEBUG
import instr3ac as INS... |
#from Evolution1.main import getLifeForms, getFoodForms, RemoveFood, RemoveLife
class Life:
name = "Generic Life Form"
x = 0
y = 0
color = "Blue"
radius = 15
Food = 0
ini_speed = 1
speed = 1
def Birth(self, surface, name, x, y, color):
self.name = name
self.x = x... |
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 20 19:45:17 2018
@author: Clement LAGNEAU
"""
import tkinter
#Rapport visible/n
k = 50
# Creation de la fenetre
fenetre = tkinter.Tk()
# Creation du canevas
canvas = tkinter.Canvas(fenetre, width=k*n, height=k*n, background='white')
#creation des lignes
for x in range... |
# ================================================================
#
# Filename: ann_digit_detect.py
# Author: Siddarth Narasimhan
# Description: Used to help train a multi-layer perceptron (ANN)
# to recognize digits. This program can be used for
# experimentation or trainin... |
from random import randint
while True:
leave_game = input("To exit press 'Q'")
leave_game = leave_game.upper
if leave_game == "Q":
break
else:
print("Pick a number from 1 to 100 and computer will guess it")
start = input("If ready press Enter: ")
|
##################################################
# Recursive Fibonacci in Python with Memoization #
#################################################
# Array for saving calculated ones
fib_mem = [0]*100000
fib_mem[0] = 0
fib_mem[1] = 1
def fibonacci(n):
# first two elements are 0 and 1
if n <= 1:
... |
import time
import random
def merge_sort(array):
"""take list and divide into two halves"""
if len(array) <= 1:
return array
l, r = merge_sort(array[:int(len(array)/2)]), merge_sort(array[int(len(array)/2):])
def merge(left, right):
"""compare the right and left sides, and ... |
S="Лесенка"
print(S)
for i in range(1,6):
A=S[:i]
B="_"
C=S[i+1:]
print(A+B+C)
|
a=2
b=3
c=1
print("Упорядочение трех чисел")
if (a>b>c):
print("max=",a,"\nmin=",c,"\nmnx=",b)
if (b>a>c):
print("max=",b,"\nmin=",c,"\nmnx=",a)
if (b>c>a):
print("max=",b,"\nmin=",a,"\nmnx=",c)
if (a>c>b):
print("max=",a,"\nmin=",b,"\nmnx=",c)
if (c>a>b):
print("max=",c,"\nmin=",b,"\nmnx=",a)
if (c... |
# -*- coding: utf-8 -*-
"""
803
請撰寫一程式,讓使用者輸入一個句子(至少有五個詞,以空白隔開),並輸出該句子倒數三個詞。
3. 輸入輸出:
輸入說明
一個句子(至少五個詞,以空白隔開)
輸出說明
該句子倒數三個詞
輸入輸出範例
範例輸入
Many foreign students study in FJU
範例輸出
study in FJU
"""
a = input()
b = a.split(' ')
print(' '.join(b[len(b)-3:]))
|
# -*- coding: utf-8 -*-
"""
Created on Thu May 28 20:44:29 2020
@author: 莫再提
"""
'''
設計說明:
請撰寫一程式,輸入X組和Y組各自的科目至集合中,以字串"end"作為結束點(集合中不包含字串"end")。請依序分行顯示(1) X組和Y組的所有科目、(2)X組和Y組的共同科目、(3)Y組有但X組沒有的科目,以及(4) X組和Y組彼此沒有的科目(不包含相同科目)。
提示:科目須參考範例輸出樣本,依字母由小至大進行排序。
3. 輸入輸出:
輸入說明
輸入X組和Y組各自的科目至集合,直至end結束輸入
輸出說明
X組和Y組的所有科目
X... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 22 14:25:48 2020
@author: ASUS
"""
#第一題
def computer(lst, a=3):
b=[]
lst.sort()
lst.reverse()
for i in range(0,a):
b.append(lst[i])
return print(b)
def main():
lst = []
for i in range(1,11):
num = eval(input("請輸... |
# -*- coding: utf-8 -*-
"""
701
2. 設計說明:
請撰寫一程式,輸入數個整數並儲存至串列中,以輸入-9999為結束點(串列中不包含-9999),
再將此串列轉換成數組,最後顯示該數組以及其長度(Length)、最大值(Max)、最小值(Min)
、總和(Sum)。
3. 輸入輸出:
輸入說明
n個整數,直至-9999結束輸入
輸出說明
數組
數組的長度
數組中的最大值
數組中的最小值
數組內的整數總和
輸入輸出範例
範例輸入
-4
0
37
19
26
-43
9
-9999
範例輸出
(-4, 0, 37, 19, 26, -43, 9)
Length: 7
Max: 37
Min: -43
... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 29 11:30:08 2020
@author: ASUS
"""
'''
802
設計說明:
請撰寫一程式,要求使用者輸入一字串,顯示該字串每個字元的對應ASCII碼及其總和。
3. 輸入輸出:
輸入說明
一個字串
輸出說明
依序輸出字串中每個字元對應的ASCII碼
每個字元ASCII碼的總和
輸入輸出範例
範例輸入
Kingdom
範例輸出
ASCII code for 'K' is 75
ASCII code for 'i' is 105
ASCII code for 'n' is 110
ASCII code for '... |
# -*- coding: utf-8 -*-
"""
請撰寫一程式,讓使用者輸入一個整數x,並將x傳遞給名為compute()的函式,此函式將回傳x是否為質數
(Prime number)的布林值,接著再將判斷結果輸出。如輸入值為質數顯示【Prime】,否則顯示
【Not Prime】。
3. 輸入輸出:
輸入說明
一個整數
輸出說明
判斷是否為質數,若為質數顯示【Prime】,否則顯示【Not Prime】
輸入輸出範例
範例輸入1
3
範例輸出1
Prime
範例輸入2
6
範例輸出2
Not Prime
範例輸入3
1
範例輸出3
Not Prime
範例輸入4
0
範例輸出4
Not Pr... |
# Model a class for a plant
class Plant:
"""docstring for Plant."""
def __init__(self, name, kingdom, family, subfamily, genus):
self.name = name
self.kingdom = kingdom
self.family = family
self.subfamily = subfamily
self.genus = genus
def describe_plant(self):
... |
class Car:
""" Simple car class """
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_mileage = 0
def get_descriptive_name(self):
long_name = f"{self.year} {self.make} {self.model}"
return long_name... |
# try:
# print(5/0)
# except ZeroDivisionError:
# print("Are you dividing by zero?")
print("Give two numbers, I'll divide the first by the second.")
print("Enter 'q' to quit.")
while True:
first_num = input("\nFirst number: ")
if first_num == 'q':
break
second_number = input("\nSecond num... |
### Imports ###
import os
import sys
import random
class Cards(object):
def __init__(self, name, year, brand, product, c_num, id_num, img):
'''
Initializes program variables
-----------------------------
self.id is a randomly generated number
self.name is ... |
from random import randint
def minimal(listn):
minim=0
for i in range(len(lst)):
if lst[i] < lst[minim]:
minim = i
return minim
lst=[randint(-10,10) for i in range(randint(4,8))]
print(lst)
minim=minimal(lst)
print(minim)
while minim!=0:
temp=lst[len(lst)-1]
lst.remove(lst[len(ls... |
BOTTOM, TOP, LEFT, RIGHT = (4, -1, -1, 17)
START_X, START_Y = (0, 0)
matrix = []
mazeMap = open('map.txt')
row_ind = 0
for row in mazeMap:
column_index = 0
matrix.append([])
for column in row:
if (column == 'S'):
start_x = row_ind;
start_y = column_index
matrix[row_ind].append({ 'Visit... |
def poluchit_nominal(a):
if a==6:
return 'Шестерка'
elif a==7:
return 'Семерка'
elif a==8:
return 'Восьмерка'
elif a==9:
return 'Девятка'
elif a==10:
return 'Десятка'
elif a==11:
return 'Валет'
elif a==12:
return 'Дама'
elif a==13:
... |
from math import sqrt
class Vector:
x=0
y=0
z=0
def __init__(self, x1, y1, z1, x2, y2, z2):
self.x=x2-x1
self.y=y2-y1
self.z=z2-z1
def printvect(self):
print(self.x, self.y, self.z)
def length(self):
return sqrt(self.x**2+self.y**2+self.z**2)
def p... |
numbers=[34, 23, 52, 46, 42, 26, 31]
for j in range(1,len(numbers)):
key=numbers[j]
i=j-1
while i>=0 and numbers[i]>key:
numbers[i+1]=numbers[i]
i=i-1
numbers[i+1]=key
print(numbers) |
from regex import regex
rgx = regex("x+y+(5z)*+2")
if rgx.isValid():
print("Everything Ok!!!")
else:
print("invalid expression! :(") |
# list
# 1. 列表倒序操作
a = [1, 2, 3]
print(a[::-1]) # [3, 2, 1]
# 2. 将一个整数分成一位个数并存于list
n3 = 807
l = list(map(int, list(str(n3)))) |
def weight(x):
return x // 3 - 2
with open('input') as infile:
data = list(map(lambda x: int(x), infile.readlines()))
res = 0
while len(data) > 0:
mod = data.pop()
w = weight(mod)
if w > 0:
res += w
data.append(w)
print(res)
|
'''
TXT-rules to ARFF-rules converter.
Input txt rules format: attr1=value,attr2=value,... -> attr3=value,...
'''
import sys
def main():
# Check number of args
if len(sys.argv) < 3:
print('\nUSAGE: python3.5 rules2arff.py [rules_file.txt] [relation_name]\n')
return
# Input file
file_name = str(sys.argv[1])
... |
# Question 1
# Given two strings s and t, determine whether some anagram of t is a substring of s.
# For example: if s = "udacity" and t = "ad", then the function returns True.
# Your function definition should look like: question1(s, t) and return a boolean True or False.
def question1(s, t):
# check for bad inp... |
suits = 'HCSD'
ranks = '9TJQKA'
def card_list_to_string(cards):
return ''.join(cards)
def card_string_to_list(card_string):
return [card_string[i:i+2] for i in range(0, len(card_string), 2)]
def card_by_index(card_string, card_index):
return card_string[2*card_index:2*card_index+2]
def move_... |
# Encrypt all pdf files in the folder with the script.
import os
import PyPDF2
from pathlib import Path
def encrypt_pdf(your_password):
"""Encrypting pdf files in current folder and saving in
the folder 'encrypted_pdfs'.
:param your_password: Password to assign to all pdf files.
"""
os.makedirs('e... |
from random import randrange
LAST = 'LAST'
LEFT = 'LEFT'
RIGHT = 'RIGHT'
class Run(object):
num_of_pots = 0
pot_list = list()
def __init__(self, _num_of_pots):
self.num_of_pots = _num_of_pots
# 금화 단위 높여서
self.pot_list = [randrange(30, 100, 5) for x in range(0, num_of_pots-1)]
... |
message_list = list()
class User_A:
nickname = ''
message_index = list()
message_count = 0
def __init__(self, _nickname):
self.nickname = _nickname
def insert(self):
text = f"{self.nickname}님이 들어왔습니다."
message_list.append(text)
self.message_index.append(message_li... |
from typing import Optional
from Crypto.Cipher import DES
from Crypto.Hash import MD5
"""
This encryptor is going to to replicate the Java jasypt encryptor by using the PBEWithMD5AndDES algorithm
"""
class PasswordBasedDeterministicEncryptor:
__default_iterations = 1000
__encoding = 'utf-8'
def __init_... |
import sqlite3
db = sqlite3.connect('tb_aspirants.db')
crsr = db.cursor()
# crsr.execute(""" create table tb_aspirants(
# MOB_NUM INTEGER NOT NULL PRIMARY KEY, NAME TEXT, MAIL_ID TEXT,LOCATION,
# HIGHEST_EDU TEXT, GRADE INTEGER,PREV_JOB TEXT,EXPERIENCE INTEGER DEFAULT 0,TECH_SKILLS TE... |
from lib.byes import is_bye as _is_bye
class Game:
""" Represents a game between two teams in a given week. If
the game was the result of a forced condition, the forced
flag is set. If the game is a bye, the is_bye flag is set.
"""
def __init__(self, home, away, week, forced=False, is_b... |
import json
import random
def data_load():
with open("data.json") as f:
data = json.load(f)
return data
def register():
data = data_load()
User = input("Enter name for User: ")
Userpassword = input("Enter password for User: ")
for i in data["user_base"].keys():
i... |
tasks = [
{ "description": "Wash Dishes", "completed": False, "time_taken": 10 },
{ "description": "Clean Windows", "completed": False, "time_taken": 15 },
{ "description": "Make Dinner", "completed": True, "time_taken": 30 },
{ "description": "Feed Cat", "completed": False, "time_taken": 5 },
{ "de... |
"""
A Node which renders text to the screen using the Pango library.
"""
import pango
import pangocairo
from Node import *
from Color import *
_STRETCH_DICT = { \
-4: pango.STRETCH_ULTRA_CONDENSED, \
-3: pango.STRETCH_EXTRA_CONDENSED, \
-2: pango.STRETCH_CONDENSED, \
-1: pango.STRETCH_SEMI_CONDENSED, \
0: pango.STRE... |
"""
An object that contains information about a detected gesture.
"""
from Geometry import *
# TODO: add state stuff so GestureListeners know if, e.g., Ctrl or Alt keys are pressed when gesture is
# TODO: dispatched.
class AbstractGestureEvent(object):
"""
An object that contains information about a detected gestu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.