text stringlengths 37 1.41M |
|---|
# -*- coding:utf-8 -*-
val1 = 1
val2 = 1
if val1 and val2:
print("A")
elif val1 or val2:
print("B")
if val1 > val2:
print("a")
elif val1 < val2:
print("b")
print("test")
val3 = ['a', 'b', 'c']
if 'a' in val3:
print(val3)
|
person = {'name':'a',
'age':30,
'phone':'01000000000'}
print(person.keys())
print(person.values())
print(person.items())
for key in person.keys():
print('key is ', key)
print('val is ', person[key])
print("-"*10)
for value in person.values():
print('val is ',value)
print("-"*10)
for (key, val) in perso... |
x = int(input("Input number to convert"))
y = []
while x > 0:
if x%2 == 1:
y.insert(0,"1")
x//=2
print(x)
elif x%2 == 0:
y.insert(0,"0")
x//=2
print(x)
print(''.join(y))
|
# Write a binary search function. It should take a sorted sequence and
# the item it is looking for. It should return the index of the item if found.
# It should return -1 if the item is not found.
def binary_search(sequence,key):
for i in range(len(sequence)):
if sequence[i] == key:
return i
... |
# 7. Create a list of tuples of first name, last name, and age for your friends and colleagues. If you don't know the age, put in None. Calculate the average age, skipping over any None values. Print out
# each name, followed by old or young if they are above or below the average age
sample_list= [('nabin','hyan',22),... |
class User:
def __init__(self, name, email):
self.name = name
self.email = email
self.account_balance = 0
# adding the deposit method
def make_deposit(self, amount): # takes an argument that is the amount of the deposit
self.account_balance += amount # the specific user's acc... |
from util import Stack
class Graph:
def __init__(self):
self.nodes = {}
def add_node(self, node):
if node not in self.nodes:
self.nodes[node] = set()
def add_edge(self, child, parent):
self.nodes[child].add(parent)
def getNeighbors(self, child):
return sel... |
# Module that contains the necessary functions to implement the VAM
# Author: Harish Balakrishnan
import numpy as np
import copy
def generate_family_of_partitions(list_of_elements):
"""
Function that generates the family of partitions
Parameters
----------
list_of_elements : list
The co... |
import zipfile
import shutil
f = open('file_one.txt', 'w+')
f.write('File one!!!')
f.close()
f = open('file_two.txt', 'w+')
f.write('File two!!!')
f.close()
comp_file = zipfile.ZipFile('comp_file.zip', 'w')
comp_file.write('file_one.txt', compress_type=zipfile.ZIP_DEFLATED)
comp_file.write('file_two.txt', compress_t... |
while 1:
try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
value = int(x)/int(y)
print('x/y is' + str(value))
except:
print ('Invalid input. Please try again')
else:
break
|
try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
print (int(x)/int(y))
except(ZeroDivisionError,TypeError,ValueError), e:
print(e)
|
try:
print "Performing an action which may throw an exception."
except Exception as error:
print "An exception was thrown!"
print str(error)
else:
print "Everything looks great!"
finally:
print "Finally is called directly after executing the try statement whether an exception is thrown or not."
|
"""
Parse humanized strings like 128M to 16K to something a machine can understand
"""
from decimal import Decimal
d = {
'k': 3,
'K': 3,
'm': 6,
'M': 6,
'b': 9,
'B': 9,
}
def parse_string(text):
""" Parse humanized strings like 128M to 16K to something a machine can understand """
... |
class Color():
BLACK = 1
RED = 2
class Node():
def __init__(self, data=None, parent=None, color=Color.RED):
self.data = data
self.parent = parent
self.color = color
self.left = self.right = None
class RBT():
def __init__(self):
self.NIL = Node(None, None, Colo... |
class Node():
def __init__(self, prev=None, data=None, next=None):
self.prev = prev
self.data = data
self.next = next
class LinkedList():
def __init__(self):
self.head = Node()
def insert(self, data):
newNode = Node(self.head, data, None)
if self.head.next !... |
lista = [0, 1, 3, 2, 23, 43, 2, 1, 5, 2, 5, 2, 56, 23, 0, -1, 2, 2]
listb = [4, 0, 1, 0, 4, 4, 4, 4, 0, 1, 1, 1,-6, 7]
def main(list):
final = {}
x = 0
while x < len(list):
if list[x] not in final:
final[list[x]] = 1
else:
final[list[x]] += 1
x += 1
fina... |
"""
1, import random
2, user input
3, function to generate a random string of same length as user input.
4, function to compare the randomly generated string to the user's string and giving it a score each time it generates and compare.
"""
import random
def random_str(user_str):
"""This function will produce a r... |
import math
#183 is a sastry number as 183184 is a #perfect square number of 432
def sastry_num(n):
"""returns True if a number n is sastry number,False otherwise"""
num = str(n) + str(n+1)
sqt = math.sqrt(int(num))
if int(sqt) - sqt == 0:
return True
return False
|
def count_all(txt):
"""gives you number of letters and digits in a string"""
dic = {"LETTERS": 0, "DIGITS": 0}
for i in txt:
if i.isnumeric():
dic["DIGITS"] += 1
elif i.isalpha():
dic["LETTERS"] += 1
else:
pass
return dic
print(count_all("roc... |
def Turtle4():
"""gives a pattern of star with a bit of 3d effect"""
import turtle
roc = turtle.Turtle()
roc.speed(0)
roc.hideturtle()
roc.getscreen().bgcolor("black")
roc.color("silver")
for i in range(1000):
i += 100
roc.forward(i)
# roc.circle(i)
roc.le... |
def largest_even(lst):
if max(lst) % 2 == 0:
return max(lst)
elif (max(lst) - 1) % 2 == 0:
return max(lst) - 1
else:
pass
lst = [3, 9, 5, 8, 4, 7, 3, 6, 6]
print(largest_even(lst)) |
class Solution:
def sortList(self, head):
if not head or not head.next:
return head
return self.merge(*list(map(self.sortList, self.split(head))))
def split(self, head):
fast = slow = head
while fast.next and fast.next.next:
fast = fast.next.next
slow = s... |
from Animal import Animal
class Cat(Animal):
# 子类中定义"hair"属性
def __init__(self):
self.hair = "短毛"
super().__init__("露露", "橘色", "2岁", "女")
# 子类中定义"catch_mouse"方法
def catch_mouse(self):
print(f"{self.name}会抓老鼠")
# 重写父类"animal_bark"方法
def animal_bark(self):
print... |
from typing import List
import timeit
# Brute Force Solution with O(n^2) complexity. Not optimal solution BUT NECESSARY to understand because it's used by
# further COMPLEX problems like 3sum and 4sum:
"""
# Optimal solution for such problems is O(n) linear time
class Solution:
def twoSum(self, nums: List[int], t... |
# My own version/implementation of Trie. This code can't be submitted to Leetcode due to
# different definition of insert and search functions. Below this
"""
class Trie:
def insert(self, word: str, currnode, index) -> None:
if index == len(word):
currnode.endFlag = True
return
... |
# Developed this on my own after reading of algorithm:
# Algorithm is : compare first element in each list, whichever ele is smaller, create its node and increment
# the pointer for that list
# Read comments for why recursive approach can lead to stackoverflow error for large lists:
# https://leetcode.com/problems/merg... |
"""Most initial Solution by me:
class Solution:
result = []
def kthSmallestutil(self, root: TreeNode, k) -> int:
if len(self.result) >= k: # If k is small, no need to store all numbers in list, helps reduce space complexity
return
if not root:
return
else:
... |
# 8iyyExWzn5PX99g
s = input('请输入一段文字:')
i = -1
while i >= -1 * len(s):
print(s[i], end="")
i = i - 1
# 麦苗儿青菜花儿黄 王东渝 |
# -*- coding:utf-8 _*-
__author__ = 'ronething'
"""
实现一个可以支持 slice 切片操作的 class
不可修改序列
"""
import numbers
class Group:
def __init__(self, group_name, company_name, staffs):
self.group_name = group_name
self.company_name = company_name
self.staffs = staffs
def __reversed__(self):
... |
# -*- coding:utf-8 _*-
__author__ = 'ronething'
import bisect
# 用来处理已排序的序列 用来维持已排序的序列 升序
# 二分查找
inter_list = []
bisect.insort(inter_list, 3)
bisect.insort(inter_list, 1)
bisect.insort(inter_list, 6)
bisect.insort(inter_list, 4)
bisect.insort(inter_list, 2)
bisect.insort(inter_list, 5)
# bisect_right or bisect_left... |
# -*- coding:utf-8 _*-
__author__ = 'ronething'
"""
tuple 比 list 好的地方
- immutable
- 性能优化
- 线程安全
- 可以作为 dict 的 key
- 拆包特性
如果拿 C lang 类比,tuple 对应 struce 、list 对应 array
"""
from collections import namedtuple
# 使用 namedtuple 创建一个类
User = namedtuple('User', ['name', 'age', 'height'])
user_tuple = ('ronet... |
# -*- coding:utf-8 _*-
__author__ = 'ronething'
"""
什么是迭代协议 __iter__
迭代器是什么 迭代器是访问集合内元素的一种方式,一般用来遍历数据
可迭代和迭代器 不一样 实现 __iter__ 可迭代 实现 __iter__ and __next__ 迭代器
"""
from collections.abc import Iterable, Iterator
a = [1, 2]
print(isinstance(a, Iterable)) # True
print(isinstance(a, Iterator)) # False
b = iter(a)
prin... |
import sys
import os.path
class dict_writer:
def __init__(self, dictionary = {}, file = "dict.txt"):
self.vars = dictionary
self.filename = file
self.does_exist = os.path.exists(self.filename)
def generate_file(self, dictionary = None):
"""
Writes the current value of ... |
import sys
def SieveOfEratosthenes(N):
# Let A be an array of Boolean values,
# indexed by integers 2 to n, initially all set to true.
primes = []
isPrime = [True] * (N + 1)
isPrime[0] = isPrime[1] = False
for i in range(int(N ** 0.5 + 1.5)):
if i > 1 :
if isPrime[i]:
for j in range(i * i, N + 1, i):
... |
for i in range(12):
table = []
for j in range(12):
table.append((i + 1) * (j + 1))
print '{:>3} {:>3} {:>3} {:>3} {:>3} {:>3} {:>3} {:>3} {:>3} {:>3} {:>3} {:>3}'.format(*table).strip()
print '\n' |
# Given two arrays write a function to find out if two arrays have the same frequency of digits.
array_1 = [1, 2, 3, 4]
array_2 = [1, 2, 3, 4]
frequency_1 = {}
frequency_2 = {}
# populate two dictionaries with key of the number in the array and the value is how frequent it shows up
def frequency(arr1, arr2, dict1, ... |
n = 0
if n%2 ==0:
print("Es par")
else:
print("No es par") |
edad = {'noe':19, 'yoselin':18, 'brendita':19}
for clave in edad:
print(edad[clave])
for clave in edad:
print (clave, edad[clave])
for clave, valor in edad.items():
print(clave, valor)
|
personajes = []
p = {'nombre':'miku uwu', 'clase':'cantante virtual', 'edad':'ni idea'}
personajes.append(p)
p = {'nombre':'kaito owo', 'clase':'cantante virtual', 'edad':'25'}
personajes.append(p)
p = {'nombre':'gummi nwn', 'clase':'cantante virtual', 'edad':'15'}
personajes.append(p)
print(personajes)
for p in pe... |
#! /home/user/miniconda3/bin/python
"""
This function gets the reverse complement
of given DNA sequences
Usage:
python reverse_complement.py <seq_file>
"""
import sys
seq_file = sys.argv[1]
def reverse_complement (seq_file:str):
complement = {'A':'T', 'C':'G', 'T':'A', 'G':'C'}
reverse_comp = "".joi... |
"""Module with values calculations"""
from typing import List
def generate_fibonacci_values(number_of_precalculated_values: int) -> List[int]:
"""
Generates fibonacci values
:param number_of_precalculated_values: number of values to calculate
:return: list of calculated values
"""
data = li... |
x = int(input())
list1 = [0]*x
for i in range(0,x):
list1[i] = int(input())
list1.sort()
print(list1) |
""" Sets are a collection of unique items. An item can be added
many times, but it will only exist once in the set"""
s = set()
s.add(1)
s.add(2)
print s
# set([1, 2])
for i in range(5):
s.add(i)
print s
# set([0, 1, 2, 3, 4])
for i in range(10):
s.add(i)
print s
# set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
"""... |
""" Take a list of items, and return a new list with items removed that do not match the filter criteria"""
# remove numbers from a list that are not even
n = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even = filter(lambda x: x % 2 == 0, n)
print even
# [2, 4, 6, 8, 10]
|
import os.path
import aes
import getpass
import random
import string
MY_PATH = os.path.abspath(os.path.dirname(__file__))
MY_PASSWORD = "justdoit"
PATH = os.path.join(MY_PATH, "config/password")
def change(old_password, password, password2, username="admin"):
"""Changing the password."""
if ... |
class MyClass:
def l(self):
li=[x**2 for x in range(1, 11)]
print(li)
def dict(self):
myDict = {x: x ** 2 for x in [1, 2, 3, 4, 5]}
print(myDict)
sDict = {x.upper(): x * 3 for x in 'coding '}
print(sDict)
tmp=MyClass()
tmp.l()
tmp.dict()
dict={1:'s',2:'ys',3:... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def helper(self, root, nodes):
if(root == None):
return 0
if(root.left == None and root.right... |
# This is a sample form for research candidates
""" Name Age Sex Weight Allergies Preferences Dislikes (Estimated Physical Activeness) (Recent Health Issues) """
print ("College Research Board")
print ("Candidates are asked to fill out the following form")
print ("To be the part of the research")
print ("Please answer... |
import random
somay = random.randrange(1, 6)
for i in range(1, 7):
print("Nhap so di ")
sonhap = int(input())
if sonhap == somay:
print("Dung roi")
break
elif sonhap < somay:
print("be qua")
elif sonhap > somay:
print("lon qua ")
|
class A(object):
def __init__(self, num):
self.num = num
def __add__(self, other):
return A(self.num + other.num)
def get_num(self):
return self.num
A.get_num = get_num
|
class A(object):
x = 1
class B(A):
pass
class C(A):
pass
print(A.x, B.x, C.x) # 1 1 1
B.x = 2
print(A.x, B.x, C.x) # 1 2 1
A.x = 3
print(A.x, B.x, C.x) # 3 2 3 tại sao vậy?
'''
C doesn’t have its own x property, independent of A.
Thus, references to C.x are in fact references to A.x
C kế thừa... |
n = 5
message = "Greater than 2" if n > 2 else "Smaller than or equal to 2"
print(message)
n = 5
message = "Hello" if n > 10 else "Goodbye" if n > 5 else "Good day"
print(message)
|
product = 1
nums = [1, 2, 3, 4]
for num in nums:
product = product * num
print(product)
from functools import reduce
product = reduce((lambda x, y: x * y), [1, 2, 3, 4])
print(product)
# Tính tổng
total = reduce(lambda a, x: a + x, [0, 1, 2, 3, 4])
print(total)
|
import json
while True:
username = input('Please input your name(q to quit): ')
if username == "q":
break
else:
filename = "usernames.json"
with open(filename, 'a') as f_obj:
username_full = '\nUsername: ' + username
json.dump(username_full, f_obj)
... |
import random
'随机数划拳'
p = int(input('请随机输入你出的剪刀(1)、石头(2)、布(3):'))
i = random.randint(1,3)
print('你出的是%d,对方出的是%d' %(p,i))
if p == i:
print('平手,再来')
elif p > 3:
print('你的出拳不合法')
elif ((p == 1 and i == 3)
or (p == 2 and i == 1)
or (p ==3 and i == 2)):
print('恭喜,你赢了')
else:
print('你输了,笨死算了')
|
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 18 10:38:31 2018
@author: SONY
"""
import tkinter
from tkinter import *
def responce():
print(ivar1.get() + ivar2.get())
root=Tk()
root.title("sum of two numbers")
ivar1=IntVar()
ivar2=IntVar()
a=Entry(textvariable=ivar1)
b=Entry(textvariable=... |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 19 18:23:32 2018
@author: SONY
"""
import tkinter
from tkinter import *
from tkinter import messagebox
root = Tk()
root.title("messagebox tkinter-7")
def showinfobox():
messagebox.showinfo("Intell-eyes","showinfo from PythonGuru")
def showwarn... |
enums = []
onums = []
while True:
num = int(input("Enter a number [0 to stop] :"))
if num == 0:
break
if num % 2 == 0:
enums.append(num)
else:
onums.append(num)
for n in sorted(enums) + sorted(onums):
print(n)
|
PI = 22/7
if __name__ == '__main__':
print("Running num_funs module")
def is_even(n):
return n % 2 == 0
def is_prime(n):
for i in range(2, n // 2 + 1):
if n % i == 0:
return False
return True
|
def validador_recursivo(m, n):
if(m == 0):
return False
if(m%10 == n):
return True
else:
return validador_recursivo(int(m/10),n);
if __name__ == "__main__":
numero = int(input("ingrese un numero : "))
digito = int(input("ingrese el digito a verificar : "))
if (validador_recursivo(nu... |
from math import *
opuesto = int(input("ingrese el valor del cateto opuesto "))
adyacente = int(input("ingrese el valor del cateto adyacente "))
hipotenusa = sqrt(opuesto**2 + adyacente**2)
print("hipotenusa = " + str(hipotenusa))
|
r = 's'
x = 0
while (r != 'N'):
x += 1
r = input(" desea continuar (S/N) ")
print("la pregunta se hizo " + str(x) + " veces ")
|
mayor = 0
menor = 0
contador = 0
acumulador = 0
while True:
numero = int(input("ingrese un numero (cero para terminar): "))
if numero == 0:
break
else:
if numero > mayor or mayor == 0:
mayor = numero
if numero < menor or menor == 0:
menor = numero
contador = contador + 1
acumulador = acumulador + nu... |
import sys
a = int(input("Ingrese el primer nmero: "))
b = int(input("Ingrese el segundo nmero: "))
if a < b :
menor = a
mayor = b
else :
menor = b
mayor = a
for i in range(menor + 1, mayor) :
if i % 2 == 0:
sys.stdout.write(str(i) + " ") |
a = int(input("Ingrese el primer numero: "))
b = int(input("Ingrese el segundo numero: "))
if a < b :
menor = a
mayor = b
else :
menor = b
mayor = a
for i in range(menor + 1, mayor) :
print(str(i),end=' ')
|
numero = int(input("ingrese el numero a evaluar: "))
if numero == 1 or numero == 3 or numero == 5 or numero == 7 or numero == 8 or numero == 10 or numero == 12:
print("31 dias")
elif numero == 2:
print("28 o 29 dias")
elif numero == 4 or numero == 6 or numero == 9 or numero == 11:
print("30 dias")
else:
print("num... |
bandera = True
agno = int(input("ingrese el agno: "))
mes = int(input("ingrese mes: "))
dia = int(input("ingrese el dia: "))
if mes < 1 or mes > 12:
bandera = False
elif mes == 1 or mes == 3 or mes == 5 or mes == 7 or mes == 8 or mes == 10 or mes == 12:
if dia > 31:
bandera = False
elif mes == 2:
if agno % 4 ==... |
""" Advent of Code 2017 Day 21 Fractal Art """
# You find a program trying to generate some art. It uses a strange process
# that involves repeatedly enhancing the detail of an image through a set of
# rules.
#
# The image consists of a two-dimensional square grid of pixels that are
# either on (#) or off (.). The ... |
"""Advent of Code 2017 Day 3 Spiral Memory"""
# You come across an experimental new kind of memory stored on an infinite
# two-dimensional grid.
#
# Each square on the grid is allocated in a spiral pattern starting at a
# location marked 1 and then counting up while spiraling outward. For
# example, the first few sq... |
""" Advent of Code 2017 Day 24 Electromagnetic Moat """
# The CPU itself is a large, black building surrounded by a bottomless pit.
# Enormous metal tubes extend outward from the side of the building at
# regular intervals and descend down into the void. There's no way to cross,
# but you need to get inside.
#
# No... |
import random
def gen_rand_list(list_size):
list_build = []
for i in range(list_size):
list_build.append(random.randint(0,100))
return list_build
def data_output():
output = open("output/list.txt",'w')
print("This will generate a list of random integers from 0 to 100 of a specified length.... |
def show_menu():
print('~~~~ Welcome to your terminal checkbook! ~~~')
print('\n'*2)
print('What would you like to do?\n')
print('1) View current balance')
print('2) Record a debit withdraw')
print('3) Record a credit deposit')
print('4) exit')
#brings up menu options
user_input = '1'
whil... |
# Task - 1
def get_user_info(username: str, age: int, current_city: str) -> str:
"""Get user info"""
return f'{username}, {age} год(а), проживает в городе {current_city}'
# Task - 2
def get_max_number(*nums) -> int:
"""Get max number"""
return max(nums)
# Task - 3-4
def attack(attacker: dict, defend... |
userListCount = int(input("Enter number of elements: "))
userList = list(map(int,input("\nEnter the numbers: ").strip().split()))
userListLen = len(userList)
getSum = sum(userList)
mean = getSum / userListLen
print("Mean: " + str(mean))
userList.sort()
if userListLen % 2 == 0:
median1 = userList[userListLen//2]
... |
########################
# Author: ~wy
# Date: 25/12/2017
# Description: Lets you play the game via CLI
########################
from Game import Game
from GameAI import GameAI
from Answer import Answer
import random
import MastermindConstants
hidden_answer_prompt = "Enter Your Hidden Answer as 4 Letter String. " \
... |
import sys
import random
vowels = ['a', 'e', 'i', 'o', 'u']
consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']
arglen = len(sys.argv)
start = 2
end = 3
limit = 10
if arglen>1: limit = int(sys.argv[1])
if arglen>2: end = int(sys.argv[2])+1
if arglen>3... |
class Singleton(type):
def __init__(cls, name, bases, dct):
cls.__instance = None
type.__init__(cls, name, bases, dct)
def __call__(cls, *args, **kw):
if cls.__instance is None:
cls.__instance = type.__call__(cls, *args,**kw)
return cls.__instance
if __name... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import UserList
import traceback
class Sortable_list(UserList.UserList):
add = UserList.UserList.append
def top(self, x):
if -len(self) <= x < len(self):
self.append(self.pop(x))
else:
traceback.extract_stack()
... |
def bigger(x,y):
return y if y>x else x
def lower(x,y):
return x if x<y else y
|
#Compute Parity of a word
#The parity of a binary word is 1 if the number of 1s in the word is odd;
#it is 0 if the number of 1s in even
#Need to count the number of 1s in a Binary word
#Better Solution (Time Complexity: O(k) where k = #1's in the word)
def better_parity(x):
'''
i/p: x, an int
o/p: 1, if... |
the_count = [1,2,3,4,5]
fruits = ['apples','oranges','pears','apricots']
change = [1,'pennies',2,'dimes',3,'dimes']
for number in the_count:
print "This is count:%d" %number
for fruit in fruits:
print "A fruit of type: %s" %fruit
for i in change:
print "i got %r" %i
# elements = []
# for i in range(0,6):
# pri... |
# creating mapiing of state and abbrevation
# the syntax given in the textbook is giving syntax errors
# changes the square brackets to curly solved it
states = {
'Oregan' : 'OR',
'Florida' : 'FL',
'California' : 'CA',
'New York' : 'NY',
'Michigan' : 'MI'
}
# create basic set of states and some cities in them
c... |
formatter = "%r %r %r %r" # %r is for raw data but the values of %r are not given.
#note the formatter is string object
# print formatter
print formatter %(1,2,3,4)
#we gave 1,2,3,4 as the 4 %r values to formatter and print.
print formatter %("one","two","three","four")
# gave String one two three four to formatter.
... |
# ex14.py
from sys import argv
script,user_name= argv #unpacking the arguments to script and user_name
prompt = '> ' #changing the value of prompt here would
# change the prompt for all raw_input
# this is taking the args
print "Hi %s i am the %s script" %(user_name,script)
print "I would like to ask you a few ques... |
import random
def game():
words=['father','mother','sister','cousin','relative','grandmother','grandfather','uncle','aunt','tire',
'love','get','redo','heady','stomach','declare','crayon','hellish','thumb','dashing','pricey','educate',
'water','closed','induce','health','restrain','point','frog','polit... |
import Tkinter as tk
top= tk.Tk();
top.title("Simple calculator")
def click(key):
if key=="=":
str1 = "0123456789."
if entry.get()[0] in str1:
result = eval(entry.get())
entry.insert(tk.END, "=" + str(result))
else:
entry.insert(tk.END,key)
butto... |
def read_input_count():
inp_file = raw_input("Enter the input File Name: ")
print inp_file
with open(inp_file, "r") as inp:
alpa_dict = {chr(k):0 for k in range(65,123)}
for line in inp:
for sub_line in line:
if sub_line in alpa_dict:
alpa_dict[sub_line] = int(alpa_dict[sub_line]) + 1
for k,v in... |
import re
# input is a list of tokens (token is a number or operator)
tokens = raw_input()
# remove whitespace
tokens = re.sub('\s+', '', tokens)
# split by addition/subtraction operators
tokens = re.split('(-|\+)', tokens)
# takes in a string of numbers, *s, and /s. returns the result
def solve_term(tokens):
t... |
def IndexWords(InputText):
count = 2
for i in range(len(InputText)):
for word in InputText[i].split()[1:]:
CapitalizationCheck = list(word.strip(','))[0].isupper()
# print(CapitalizationCheck)
if CapitalizationCheck == True:
print('%s:%s' % (c... |
# Random Selection
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#Importing the Dataset
dataset = pd.read_csv('Ads_CTR_Optimisation.csv')
# Implementing Random Selection
import random
N= 10000
d = 10
ads_selected = []
total_rewards = 0
for n in r... |
# K means Clusterning
#Importing the Libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Importing the dataset
dataset = pd.read_csv("Mall_Customers.csv")
X = dataset.iloc[:,[3,4]].values
# Using elbow method to find optimal number of clusters
from sklearn.cluster import... |
"""
As discussed in the last approach, once we've fixed a nums[i],nums[j]nums[i],nums[j] pair, we just need to determine a nums[k]nums[k] which falls in the range (nums[i],nums[j])(nums[i],nums[j]). Further, to maximize the likelihood of any arbitrary nums[k]nums[k] falling in this range, we need to try to keep this ra... |
from tkinter import * # импортировать виджет
widget = Label(None, text='Hello GUI world!') # создать его
widget.pack(expand=YES, fill=BOTH) # разместить
widget.mainloop() # запустить цикл событий |
"всегда выводит 200 - благодаря синхронизации доступа к глобальному ресурсу"
import threading, time
count = 0
def adder(addlock): # совместно используемый объект блокировки
global count
with addlock: # блокировка приобретается/освобождается
count = count + 1 # автоматически
time.sleep(... |
"""
отображает изображение с помощью альтернативного объекта из пакета PIL
поддерживает множество форматов изображений; предварительно установите пакет
PIL: поместите его в каталог Lib\site-packages
"""
import os, sys, random
from glob import glob # чтобы получить список файлов по расширению
from tkinter import *
fro... |
# проверка состояния флажков, простой способ
from tkinter import *
root = Tk()
states = []
for i in range(10):
var = IntVar()
chk = Checkbutton(root, text=str(i), variable=var)
chk.pack(side=LEFT)
states.append(var)
root.mainloop() # пусть следит библ иотека tkinter
print([var.get()... |
# 提示输入的三个数以空格隔开,并判断最大的数
string1 = input("请输入三个数字,数字之间用空格隔开:")
client1 = string1.split(" ", string1.count(" "))
print(client1)
if int(client1[0]) > int(client1[1]) and int(client1[0]) > int(client1[2]):
print("您输入的最大数字为:%s" % (client1[0]))
elif int(client1[1]) > int(client1[0]) and int(client1[1]) > int(client... |
# -*- coding:utf-8 -*-
import time
import datetime
localtime = time.localtime(time.time())
print(localtime)
print(time.asctime())
print(time.asctime(time.localtime(time.time())))
print(time.strftime("%Y-%m-%d %H:%M:%S"))
def count():
fs = []
for i in range(1, 4):
def f(j):
de... |
#!usr/bin/python
# coding=utf-8
'''基于python套接字的半双工通讯实现客户端同服务器的对话(对讲机)'''
import socket
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #创建socket对象
sock.bind(('',9001)) #创建服务器端口
print('this is server...,I am OK')
sock.listen(60) #设置服务器最大监听数
con,add = sock.accept()
while True:
recvs = con.rec... |
#Used for dealing with time
from datetime import datetime, date, time
def now():
#returns the current time as a timestamp
return datetime.timestamp(datetime.now())
def difference(initialTime):
#returns the tifference between the timestamps in minutes in float type
return (datetime.timestamp(datetime.n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.