text stringlengths 37 1.41M |
|---|
num = 1
while num < 11:
if num %2 == 0:
print num
num += 1
print 'Goodbye!' |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import sys, os
sys.path.append(os.pardir)
import numpy as np
# In[2]:
class MulLayer:
def __init__(self):
self.x = None
self.y = None
def forward(self, x, y):
self.x = x
self.y = y
out = x * y
... |
"""
Given an array of size n, find the most common and the least common elements.
The most common element is the element that appears more than n // 2 times.
The least common element is the element that appears fewer than other.
You may assume that the array is non-empty and the most common element
always exist in the ... |
from typing import Sequence
def build_fibonacci(x: int):
fib_seq = [0, 1]
current = 0
while current < x:
current = fib_seq[-1] + fib_seq[-2]
fib_seq.append(current)
return fib_seq
def find_start(fib_seq: Sequence[int], data: Sequence[int]):
ans = -1
for i in range(len(fib_seq... |
#!/usr/bin/env python3
# Day 10: Excel Sheet Column Number
#
# Given a column title as appear in an Excel sheet, return its corresponding
# column number.
# A = 1
# B = 2
# C = 3
# ...
# Z = 26
# AA = 27
# AB = 28
# ...
class Solution:
def titleToNumber(self, s: str) -> int:
# In other words, convert from... |
#!/usr/bin/env python3
# Day 1: Largest Time for Given Digits
#
# Given an array of 4 digits, return the largest 24 hour time that can be made.
# The smallest 24 hour time is 00:00, and the largest is 23:59. Starting from
# 00:00, a time is larger if more time has elapsed since midnight.
# Return the answer as a strin... |
#!/usr/bin/env python3
# Day 14: Cheapest Flights Within K Stops
#
# There are n cities connected by m flights. Each flight starts from city u and
# arrives at v with a price w.
# Now given all the cities and flights, together with starting city src and the
# destination dst, your task is to find the cheapest price fr... |
#!/usr/bin/env python3
# Day 20: Reorder List
#
# Given a singly linked list L: L0→L1→…→Ln-1→Ln,
# reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
# You may not modify the values in the list's nodes, only nodes itself may be
# changed.
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=Non... |
#!/usr/bin/env python3
# Day 29: Best Time to Buy and Sell Stock with Cooldown
#
# Say you have an array for which the ith element is the price of a given stock
# on day i.
# Design an algorithm to find the maximum profit. You may complete as many
# transactions as you like (ie, buy one and sell one share of the stock... |
#!/usr/bin/env python3
# Day 30: Check If a String Is a Valid Sequence from Root to Leaves Path in a
# Binary Tree
#
# Given a binary tree where each path going from the root to any leaf form a
# valid sequence, check if a given string is a valid sequence in such binary
# tree.
# We get the given string from the conc... |
#!/usr/bin/env python3
# Day 13: Same Tree
#
# Given two binary trees, write a function to check if they are the same or
# not.
# Two binary trees are considered the same if they are structurally identical
# and the nodes have the same value.
# Definition for a binary tree node.
class TreeNode:
def __init__(self,... |
#!/usr/bin/env python3
# Day 26: Add Digits
#
# Given a non-negative integer num, repeatedly add all its digits until the
# result has only one digit.
# Could you do it without any loop/recursion in O(1) runtime?
class Solution:
def addDigits(self, num: int) -> int:
if num == 0:
return 0
... |
#!/usr/bin/env python3
# Day 27: Construct Binary Tree from Inorder and Postorder Traversal
#
# Given inorder and postorder traversal of a tree, construct the binary tree.
#
# Note:
# - You may assume that duplicates do not exist in the tree.
# Definition for a binary tree node.
class TreeNode:
def __init__(self,... |
#!/usr/bin/env python3
# Day 31: Climbing Stairs
#
# You are climbing a stair case. It takes n steps to reach to the top.
# Each time you can either climb 1 or 2 steps. In how many distinct ways can
# you climb to the top?
import math
class Solution:
def climbStairs(self, n: int) -> int:
# Hello Fibonnac... |
#!/usr/bin/env python3
# Day 24: LRU Cache
#
# Design and implement a data structure for Least Recently Used (LRU) cache. It
# should support the following operations: get and put.
# - get(key) - Get the value (will always be positive) of the key if the key
# exists in the cache, otherwise return -1.
# - put(key, va... |
#!/usr/bin/env python3
# Day 9: Rotting Oranges
#
# In a given grid, each cell can have one of three values:
# - the value 0 representing an empty cell;
# - the value 1 representing a fresh orange;
# - the value 2 representing a rotten orange.
#
# Every minute, any fresh orange that is adjacent (4-directionally) to a ... |
#!/usr/bin/env python3
# Day 12: Pascal's Triangle II
#
# Given a non-negative index k where k ≤ 33, return the kth index row of the
# Pascal's triangle.
# Note that the row index starts from 0.
class Solution:
def getRow(self, rowIndex: int) -> [int]:
# Given the maximum input size a direct approach does... |
#!/usr/bin/env python3
# Day 21: Sort Array By Parity
#
# Given an array A of non-negative integers, return an array consisting of all
# the even elements of A, followed by all the odd elements of A.
# You may return any answer array that satisfies this condition.
#
# Note:
# - 1 <= A.length <= 5000
# - 0 <= A[i] <= 5... |
#!/usr/bin/env python3
# Day 11: Flood Fill
#
# An image is represented by a 2-D array of integers, each integer representing
# the pixel value of the image (from 0 to 65535).
# Given a coordinate (sr, sc) representing the starting pixel (row and column)
# of the flood fill, and a pixel value newColor, "flood fill" th... |
#!/usr/bin/env python3
# Day 20: Kth Smallest Element in a BST
#
# Given a binary search tree, write a function kthSmallest to find the kth
# smallest element in it.
#
# Note:
# - You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
# Definition for a binary tree node.
class TreeNode:
def __init__(self... |
#!/usr/bin/env python3
# Day 16: Odd Even Linked List
#
# Given a singly linked list, group all odd nodes together followed by the even
# nodes. Please note here we are talking about the node number and not the
# value in the nodes.
# You should try to do it in place. The program should run in O(1) space
# complexity ... |
#!/usr/bin/env python3
# Day 8: Power of Two
#
# Given an integer, write a function to determine if it is a power of two.
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and (n & (n - 1)) == 0
# Tests
assert Solution().isPowerOfTwo(1) == True
assert Solution().isPowerOfTwo(16) == Tru... |
#!/usr/bin/env python3
# Day 28: First Unique Number
#
# You have a queue of integers, you need to retrieve the first unique integer
# in the queue.
# Implement the FirstUnique class:
# - FirstUnique(int[] nums) Initializes the object with the numbers in the
# queue.
# - int showFirstUnique() returns the value of th... |
#!/usr/bin/env python3
# Day 20: Permutation Sequence
#
# The set [1,2,3,...,n] contains a total of n! unique permutations.
# By listing and labeling all of the permutations in order, we get the
# following sequence for n = 3:
# 1 - "123"
# 2 - "132"
# 3 - "213"
# 4 - "231"
# 5 - "312"
# 6 - "321"
#
# Given n and k, r... |
age=raw_input("enter your age ")
height=raw_input("enter your height ")
weight=raw_input("enter your weight ")
print "age %r height %r weight %r" % (age,height,weight)
|
#test a syntax
import random
test_list=['chandan','nithish','sanju']
test_list2=['abc','xyz']
new_var1=random.sample(test_list,1)
new_var2=random.sample(test_list2,1)
#print new_var1
#print new_var2
for loop_var in new_var1,new_var2:
final_list=loop_var[:]
for i in range(0,len(final_list)):
print final_list
|
#function with runtime arguments
def arg_run(*args):
arg1,arg2=args
print "the two arguments %r and %r" % (arg1,arg2)
def arg_one(arg1):
print "the argument one is %r" % (arg1)
def arg_two(arg1,arg2):
print "the two arguments are %r and %r" % (arg1,arg2)
def arg_none():
print "function with no argu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/5/23 10:52
# @Author : xc
# @Site :
# @File : practise.py
# @Software: PyCharm
import random
def count_sort(li, max_num):
count = [0 for i in range(max_num + 1)]
for num in li:
count[num] += 1
i = 0
for num, m in enumerat... |
import numpy as np
from sklearn.base import BaseEstimator
from sklearn.svm import LinearSVC
class UniformOVA(BaseEstimator):
'''
UniformOVA estimator fits a linear SVC model for each class that has
data, and a NullModel for any classes with no positive instances.
It predicts class membership whenever ... |
# expression
# HCF
# LCM
# POWER
# POWER ROOT
# FACTORIAL
# CONVERSION raidian to degre
# CONVERSION degree to radian
# trignametry function
import math
import datetime
def expr(a):
return eval(a)
def hcf(q,w):
t=math.gcd(q,w)
return t
def lc(x1,x2):
lcm=(x1*x2)/math.gcd(x1,x2)
return lcm
def ... |
def reverse(n):
rev=0
while(n!=0):
r=n%10
rev=rev*10+r
n=n//10
return rev
x=int(input("\nenter a number:\t"))
y=reverse(x)
print("\nReverse of the number is \t",y)
input() |
x=int(input("Enter a Number : \t"))
n=x
z=0
while(x!=0):
y=x%10
z=z+(y*y*y)
x=x//10
if(z==n):
print("This is armstrong number:\t",z)
else:
print("\nThis is not armstrong Number:\t",n)
input() |
x=int(input("Enter a number="))
sum=0 #for sum of the factor
c=0 #for count of the factor
for i in range(1,x+1):
if(x%i==0):
print(i)
sum=sum+i #for sum of the factor
c=c+1 #for count of the factor
print("number of factor are=",c)
print("sum of factor=",sum)
input()
|
eid=int(input("Enter the eid:"))
ename=input("Enter the ename:")
esal=float(input("Enter the esal:"))
print("Emp id:",eid)
print("Emp name:",ename)
print("Emp sal:",esal)
print(eid,ename,esal)
print("Emp id=%d , Emp name=%s , Emp sal=%g"%(eid,ename,esal))
print("Emp id={0} Emp name={1} Emp sal={2}".format(eid,ename... |
def cripto(word):
cpy=list(word[:])
for x in range(len(word)):
if word[x]>='a' and word[x]<='z' or word[x]>='A' and word[x]<='Z':
cpy[x]=chr(ord(word[x]) + 3)
cpy=cpy[::-1];l=len(word)
for m in range(l/2, l):
cpy[m]=chr(ord(cpy[m])-1)
retu... |
number = float(input())
if number < 0.0000:
print "Fora de intervalo\n"
elif number >=0.0000 and number <= 25.0000:
print "Intervalo [0,25]\n"
elif number > 25.0000 and number <= 50.0000:
print "Intervalo (25,50]\n"
elif number > 50.0000 and number <= 75.0000:
print "Intervalo (50,75]\n"
eli... |
#!/usr/bin/env python
import requests
from pprint import pprint
def main():
'''A weather application that shows the weather of a city and its temparature '''
city= "Nairobi"
response = requests.get("http://api.openweathermap.org/data/2.5/weather?q="+city+"&appid=31cb387d5a46c10fe1e0400a04d0721f&units=metric")
asse... |
# -*- coding: utf-8 -*-
__author__ = "Arkadiusz Wos"
__copyright__ = "Arkadiusz Wos"
__version__ = "1.0"
__email__ = "arkadiusz.wos@gmail.com"
"""
Script to loop through 2 numbers(n,m) set by User and print accoring rules:
● for multiples of three, print Fizz (instead of the number)
● for multiples of five, p... |
#ctrl + / will comment or uncomment block of code in pychrm
print ("hi")
print ("all")
string_1 = 'P'
string_2 = "\U00000050"
print(string_1)
print(string_2)
num_1 = 1.22
str_1 = str(num_1)
print(num_1)
print(type(num_1))
print(str_1)
print(type(str_1))
num_2 = int(num_1)
print(num_2)
print(type(num_2))
result = inp... |
from enum import Enum
class CellStates(Enum):
EMPTY = 1
START = 2
GOAL = 3
TRAP = 4
WALL = 5
class Actions(Enum):
UP = 1
RIGHT = 2
DOWN = 3
LEFT = 4
class Agent():
def __init__(self, pos):
self.pos = pos
class Cell():
def __init__(self, pos, init_state):
s... |
#Program to calculate and display a user's bonus based on sales.
#If sales are under $1,000, the user gets a 10% bonus.
#If sales are $1,000 or over, the bonus is 15%.
MENU = "Sales Bonus"
print(MENU)
sales = float (input("enter sales: $"))
if sales < 1000 :
bonus = sales * 0.1
print("Bonus is $", bonus, sep=''... |
import datetime
from banner import banner
banner("Birthday", "Isiah.C")
#process
# 1. Find out birthday from user
# 2. Calculate how many days apart that is from now
# 3. Print the birthday info, Days to go, Days ago, or Happy Birthday
def main():
birthday = get_birthday_from_user()
now = datetime.date.toda... |
# The [] brackets are used for lists.
my_list = [1,2,3] # A list of integers.
# You can also create a list with varying object types.
my_other_list = [1, 'hey', 1.2]
#The fucntion 'len', can be used to idenfity the number of variables within the list.
print(len(my_other_list)) # The len function wi... |
#Reference: https://github.com/amir-jafari/Deep-Learning
import torch
import torch.nn as nn
#define class for MLP
class Net(nn.Module):
def __init__(self, input_size, hidden_size, num_classes, activation):
super(Net, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size1)
self.relu1... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2019-01-03 20:24
# @Author: jiaxiong
# @File : list_tuple.py
# list to tuple
myList = [1, 2, 3, 4, 1]
print(myList)
print(type(myList))
myList_tp = tuple(myList)
print(myList_tp)
print(type(myList_tp))
print('*'*20)
# tuple to list
myTuple = (5, 6, 7, 8, 5)
pri... |
def parse_input(file_location: str):
with open(file_location, "r") as file:
arr = []
for line in file.readlines():
outer, inner = line.strip().split(" bags contain ")
if inner == "no other bags.":
inner_arr = ()
else:
inner.replace(... |
import turtle
import random
turtle.speed(0)
def coondinate(x, y):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
def screen_drow(x, y, r):
turtle.fillcolor(random.random(), random.random(), random.random())
turtle.begin_fill()
coondinate(x, y)
turtle.circle(r)
turtle.end_fill()
... |
# Задача: используя цикл запрашивайте у пользователя число пока оно не станет больше 0, но меньше 10.
# После того, как пользователь введет корректное число, возведите его в степерь 2 и выведите на экран.
# Например, пользователь вводит число 123, вы сообщаете ему, что число не верное,
# и сообщаете об диапазоне допуст... |
# Задание - 1
# Давайте опишем пару сущностей player и enemy через словарь,
# который будет иметь ключи и значения:
# name - строка полученная от пользователя,
# health - 100,
# damage - 50.
# Поэксперементируйте с значениями урона и жизней по желанию.
# Теперь надо создать функцию attack(person1, person2), аргументы м... |
## 切片:想获取多个字符的时候,你有把刀,去切这个字符串
name = "yuze wang"
# 开始位置和结束位置
# 公式1: 字符串[start:end]
# uz, e 不在里面 :顾头不顾腚, 骨头不顾尾
print(name[1:3])
print(name[0:5])
# 公式2: 字符串[start:end:step]
# 0,2,4
# 0, 3,
print(name[0:6:3])
# 公式3: 字符串[start:]
print(name[1:])
print(name[:6])
# 复制
print(name[:]) #
name_cp = name[:]
print(name_cp)
#... |
"""
直接使用 logging 有一下问题:
- info 信息没有产生
- 文件输出日志
- 时间,运行日志的位置。
最好不要直接用 logging.info 这样的操作。
学习的时候:帮助我们理解 logging 的概念
"""
import logging
class Dog():
def __init__(self, color):
logging.info("正在初始化")
self.color = color
logging.info("获取属性 color ")
self.ke = "dog"
logging.warnin... |
"""
1、现在有字符串:str1 = 'python cainiao 666'
1、请找出第 5 个字符。
2、请找出第 3 到 第 8 个字符。
"""
str1 = 'python cainiao 666'
# print(str1[4])
#
# # 是不是复制, 切片复制, copy
"""
2、卖橘子的计算器:写一段代码,提示用户输入橘子的价格,和重量,最后计算出应该支付的金额!(不需要校验数据,都传入数字就可以了。)
"""
price = input("价格")
weight = input("重量")
print(float(price) * float(weight) )
"""
... |
# name = "gao yang"
# print(name.count(" "))
#
#
# print(name.replace("gao","GAO"))
number = "123456"
print(number.count("2"))
new_number = ".".join(["花蝶", "花花世界", "飞舞"])
print(new_number)
print("我爱" + "你")
print(number.replace("1", "0"))
print(number.split('2'))
name = " gaoyang "
print(name)
print(name.str... |
"""
开发写的后端接口
"""
import time
from flask import Flask, request
server = Flask(__name__)
@server.route('/')
def index():
# 获取 token
token = request.args.get('t', '')
if not token:
return {"msg": "login first, get token"}
user = token.split('@')[0]
token_start_time = token.split('@')[1]
... |
def Expose(func):
"""
This is to prevent methods that aren't supposed to be able to be
called from being called through wild-card method-name-based
routing systems.
"""
# Checks to make sure that the method has not been previously prevented from
# being exposed (Currently only a Filter would do this).
i... |
#!/usr/bin/env python
# Required imports
import sys
from utils import *
from datetime import datetime
class ConsumerComplaints:
"""
This class takes csv file path as input, filters data based on given criteria and writes back to another csv file
...
Attributes
----------
filter... |
def zigzag(n):
indexorder = sorted(((x,y) for x in range(n) for y in range(n)),
key=lambda (x, y): (x+y, -y if (x+y) % 2 else y))
return indexorder
def triangle(n):
tri_matrix = [[1 for i in range(n-j-1)] + [0 for i in range(j+1)] for j in range(n)]
return tri_matrix
|
# Python program to print
# mean of elements
# list of elements to calculate mean
n_num = [1, 2, 3, 4, 5]
n = len(n_num)
get_sum = sum(n_num)
mean = get_sum / n
print("Mean / Average is: " + str(mean))
|
class TreeNode():
def __init__(self, value):
self.value = value
self.right = None
self.left = None
def getValue(self):
return self.value
def setLeftChild(self, left):
self.left = left
def setRightChild(self, right):
self.right = right
... |
def calculateLongitudeZone(coordinates):
longitude = coordinates[0]
relative_longitude = format((longitude - 144.7), '.8f')
relative_longitude = float(relative_longitude)
print(relative_longitude)
if relative_longitude < 0 or relative_longitude > 0.6:
# Stop searching this twitter
lo... |
from tkinter import *
def showTable():
# table will store the value that we enter, get() is used to get the String value
table = entry.get()
two = int(table) * 2
three = int(table) * 3
four = int(table) * 4
five = int(table) * 5
six = int(table) * 6
seven = int(table) * 7
... |
word = input('Input a word and watch it grow!: ')
print(word.upper())
|
############ lesson2_item4_step8.py
'''
Открыть страницу http://suninjuly.github.io/explicit_wait2.html
Дождаться, когда цена дома уменьшится до $100 (ожидание нужно установить не меньше 12 секунд)
Нажать на кнопку "Book"
Решить уже известную нам математическую задачу (используйте ранее написанны... |
import random
from enum import IntEnum
class Action(IntEnum):
Rock = 0
Paper = 1
Scissors = 2
def user_pick():
choices = [f'{action.name}[{action.value}]' for action in Action]
choices_str = ', '.join(choices)
selection = int(input(f'enter a choice {choices_str}):'))
action = Action(select... |
# Binary Search algorithm using recursion
# Binary Search function that return the position of the element to find
# Takes the array, element to find, l is set to first element and h is set to last element
def binary_search(arr, ele, l, h):
if h - l < 0:
return None
mid = (h + l) // 2
if ar... |
#! /bin/env python3
''' Class that represents a bit mask.
It has methods representing all
the bitwise operations plus some
additional features. The methods
return a new BitMask object or
a boolean result. See the bits
module for more on the operations
provided.
'''
# For testing API, "BitMask" API can be "see".
__all_... |
'''
Created on Feb 23, 2016
@author: dj
'''
class Circle1(object):
def __init__(self, radius):
self.__radius = radius
def set_radius(self, newValue):
if newValue >= 0:
self.__radius = newValue
else:
raise ValueError("Value must be positive")
def area(sel... |
'''
Created on Feb 22, 2016
@author: dj
'''
def fibonacci():
numbers = []
while True:
if len(numbers) < 2:
numbers.append(1)
else:
numbers.append(sum(numbers))
numbers.pop(0)
yield numbers[-1]
def main():
print("-" * 40)
for n in fibonacc... |
'''
Created on Apr 1, 2016
@author: dj
'''
from collections import namedtuple
print("-" * 40)
Person = namedtuple("Person", "name age gender")
tom = Person("Tom", 10, "M")
print("Tom is", tom)
jerry = Person(gender="M", name="Jerry", age=8)
print("Jerry is", jerry)
mary_info = {"name": "Mary", "age": 15, "gender... |
'''
Created on Apr 4, 2016
@author: dj
'''
import pickle
class Person(object):
name = ""
age = 0
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return self.__class__.__name__ + ":{name}, {age}".format(**vars(self))
def main():
person... |
n=input()
l=[]
for i in range(n):
t=input()
l.append(t)
l.sort()
for i in l:
print i
|
class Solution:
"""
@param words: a list of string
@return: a boolean
"""
def validWordSquare(self, words):
# Write your code here
N = len(words)
if N != len(words[0]):
return False
for i in range(N):
for j in range(i + 1, N):
... |
ans=0
for i in range(1,1000):
if (i%3==0 or i%5==0):
ans+=i
print(ans)
|
def gcd(x,y):
return y if (x%y==0) else gcd(y,x%y)
def lcm(x,y):
return x//gcd(x,y)*y
ans=1
for i in range(1,21):
ans=lcm(ans,i)
print(ans)
|
sym = input()
flag_1 = 0
flag_2 = 0
#for i in range(ord('A'), ord('Z') + 1):
if ord(sym) == ord('A') or ord(sym) == ord('Z') or ord(sym) > ord('A') and ord(sym) < ord('Z'):
flag_1 += 1
#for a in range(ord('a'), ord('z') + 1):
if ord(sym) == ord('a') or ord(sym) == ord('z') or ord(sym) > ord('a') and ord(sym) <... |
num = int(input())
total = 0
counter = 0
while num != 0:
total += num
counter += 1
num = int(input())
total = total / counter
print(total)
|
n = int(input())
counter = 0
for i in range(1, n + 1):
num = i % 10
if num == 5:
counter += 1
print(counter)
|
import random
print('Hello, you came to play the game "Guess the number"')
print('Enter the number to which you would like to guess :) :', end=' ')
n = int(input())
def is_valid(user_input):
global n
if user_input.isdigit():
user_number = int(user_input)
if user_number >= 1 and u... |
a = int(input())
counter = 0
while a != 0:
last_digit = a % 10
if last_digit == 5:
counter += 1
a = a // 10
print(counter)
|
print('Введите текст:')
text = input()
print('Есть ли в этом тексте упоминание о "Glo Academy"?')
if 'Glo Academy' in text:
print('YES')
else:
print('NO')
|
num = int(input())
list = []
for i in range(num):
string = input()
#s = string.lower()
list.append(string)
print(list)
query = input()
for a in range(len(list)):
if list[a].lower().count(query):
print(list[a])
#print(list[a])
|
#!/usr/local/bin/python
import sys
try:
# open file stream
file = open(file_name, "w")
except IOError:
print "There was an error writing to", file_name
sys.exit()
print "Enter '", file_finish;
print "' When finished"
print '7'
while file_text != file_finish:
file_text = raw_input("Enter text: ")
i... |
n=int(input("Enter number: "))
x=21-n
if n<=21:
print(x," is the absolute diff")
else:
x*=(-2)
print(x," is the absolute diff") |
import sqlite3 as db
conn = db.connect('test.db')
cursor = conn.cursor()
cursor.execute("drop table if exists temps")
cursor.execute("create table temps(date text, temp int)")
cursor.execute("insert into temps values('09/01/2015', 35)")
cursor.execute("insert into temps values('09/02/2015', 42)")
cursor.execute("inse... |
import os
os.system('cls')
beatles = ['John', 'Paul', 'George', 'Ringo']
print(beatles)
print(len(beatles))
print(beatles[0])
print(beatles[1:])
print(beatles[0:2])
print(beatles[2:4])
#print in sorted order
print(sorted(beatles))
#permanently sort list
beatles.sort()
print(beatles)
#permanently reverse list
bea... |
class Node:
def __init__(self, ID, connections=None):
"""
:param ID: This node's ID
:param connections: A list of edges that connect this node to its neighbors
:param community: The community that this node is a part of
"""
self.ID = ID
self.community = None... |
import sys
def prompt(text: str):
print(text)
def prompt_input(prompt: str, default: str = None):
if default is not None:
prompt += f' [{default}]'
prompt += ': '
res = input(prompt)
if res == '':
res = default
return res
def error(prompt):
print(prompt, file=sys.stderr... |
#Shriram Rangarajan
#MISM BIDA - Pyhton capstone
#Activity 2
#In this activity we strip of all html tags and display only the text content in the website
import urllib.request
from bs4 import BeautifulSoup
web_url = "http://www.opera.com/docs/changelogs/unified/2600/"
request_content = urllib.request.urlopen(web_url)
#... |
# Input dari user
# data yg dimasukkan pasti string
data = input("Masukkan data: ")
print("data =", data, ",type =", type(data))
# jika ingin mengambil data int dan float, maka
angka = int(input("Masukkan data: "))
angka = float(input("Masukkan data: "))
print("data =", angka, ",type =", type(angka))
# ji... |
#!/usr/bin/python
import sys
from random import shuffle, seed
from itertools import product
class Card:
FACES = {11: 'Jack', 12: 'Queen', 13: 'King', 14: 'Ace'}
SUITS = {'Hearts': 1, 'Diamonds': 2, 'Spades': 3, 'Clubs': 4}
COLORS = {'Hearts': 0, 'Diamonds': 0, 'Spades': 1, 'Clubs': 1}
def __init__(s... |
a=float(input("enter the temp in celsius:"))
b=a+273.15
print("temperature in kelvin ",b)
|
"""Модуль тестирования"""
import unittest
from unittest.mock import patch
from game import Game
import core_classes
import algorithms
import copy
import json
import os
class TestAlgorithms(unittest.TestCase):
"""Класс тестирует алгоритмы, находящиеся в модуле algorithms"""
def test_line(self):
"""Ме... |
"""
Program to run game of life in a loop, and get values for equilibrium time
Histogram is then obtained from these equilibrium values
"""
import sys
import time
import random
import numpy as np
from typing import no_type_check
import matplotlib
matplotlib.use('TKAgg')
import matplotlib.pyplot as pl... |
#!C:\Python34
x={'1':'2','2':'3','3':'4'}
for key in x:
print (key, x[key])
|
#!C:\Python34
def swapbits(x,y,posx,posy, bits):
print (" original x ", '{0:08b}'.format(x), end = "\n")
print (" original y ", '{0:08b}'.format(y), end = "\n")
#print mask for x
x_mask=(1<<bits)-1
print (" mask ", '{0:08b}'.format(x_mask), end = "\n")
x_mask=x_mask<<(posx-bits)
print (" mask after bits sh... |
#!C:\Python34
a,b,c= eval(input("Enter three numbers "))
print ("a= " , a, "b= ", b , "c= ", c)
if (a<b and a<c):
print (a , "is smaller")
elif ( b<c and b <a):
print (b , "is smaller")
else:
print (c , "is smaller") |
#!/usr/bin/python
class SpeedLimitError(Exception):
"""Base Class for User definded Exception"""
def __inti__(self, speed):
self.speed =speed
def __str__(self):
return "Speed is "+str(self.speed)
class SpeedBelowLimit(SpeedLimitError):
"""Speed below Limit Execption"""
def __init__(self, speed):
SpeedLimit... |
def factorial(no):
if(no==0):
return no
if(no==1):
return no
fact=1
for x in range (1, no+1):
fact =fact* x
return fact
#no = eval(input ("enter use from n "))
f= factorial(5)
print (f) |
#!C:\Python34
import shutil
def zip_file(path, folder):
shutil.make_archive('myarchive', 'zip', path , folder)
def main():
folder= input("Enter folder: ")
path = input("Enter path for zip" )
zip_file(path, folder)
if __name__=="__main__":
main() |
def first_position(s):
s2 = ''
s = str(s)
for i in range(0,len(s)):
if s[i] not in s2:
print('First position of {} is {}'.format(s[i],i))
s2 = s2 + s[i]
first_position(10122334455887667)
exit() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.