text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python
# encoding: utf-8
"""
@author: Kimmyzhang
@license: Apache Licence
@file: kimmyzhang_20170911_03.py
@time: 2017/9/11 17:01
"""
# 尽量不要重复代码
def get_max_index(nums):
len_nums = len(nums)
max_num = max(nums)
max_index = []
for i in range(len_nums):
if nums[... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @date : 2018-05-05 16:22:39
# @author : lyrichu
# @email :919987476@qq.com
# @link : https://www.github.com/Lyrichu
# @version : 0.1
# @description:
'''
Q3:给定一个链表a1->a2->...->an,返回a1->an->a2->a(n-1)->...
tips:将链表从中间一分为二,然后转换为链表插入问题
'''
class Node:
def __init__(... |
# 当我们在传入函数时,有些时候,不需要显示的定义函数,直接传入匿名函数更方便。
lambda x: x * x
# 上面这个匿名函数就是:
def f(x):
return x * x
# 匿名函数有一个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果。
# 匿名函数有个好处,因为函数没有名字,不必担心函数名冲突。此外,匿名函数也是一个函数对象,也可以把匿名函数复制给一个变量,然后再利用变量来调用该函数
f = lambda x:x * x
print(f(4))
# 同样,可以把匿名函数作为返回值返回
def build(x, y):
return lambda: x * x + y *... |
# python 内建的 filter() 函数用于过滤序列;
# fitter() 把传入的函数一次作用与每个元素,然后根据返回值是True 还是 False 决定保留还是丢弃该元素
# 例如:在一个list中,删掉偶数,只保留奇数:
def is_off(n):
return n % 2 == 1
L = list(filter(is_off, [1,2,3,4,5,6,8,9]))
print(L)
# 求出素数
# 先构造一个从3开始的奇数序列
def _odd_iter():
n = 1
while True:
n = n + 2
yield n
# 再定义一个筛选... |
# tuple类型数据,叫元组,也是一种有序列表,tuple一旦初始化就不能更改。写代码的时候,可以利用其不可变的特性,使代码变得更安全。
a = ('white', 'yellow', 'red')
print(a)
print(a[0])
print(a[1])
print(a[2])
print(a[-1])
print(a[-2])
print(a[-3])
# 定义一个空的tuple
b = ()
print(b)
# 如果要定义一个只有1个元素的tuple,就需要注意了
c = (1)
print(c)
# 这时候定义的就不是tuple,而是 1 这个数,这是因为括号()既可以表示tuple,又可以表示数学公式中的小... |
# this is the class and the methods
class Budget:
def __init__(self, balance):
self.balance = balance
def deposit(self, amount):
self.balance = self.balance + amount
return self.balance
def withdraw(self, amount):
self.balance = self.balance - amount
retu... |
import numpy as NP
from matplotlib import pyplot as PT
from operator import itemgetter
class KNN(object):
"""
Class provides implementation of classification
problem via k-Nearest Neighbour Algorithm.
Given a training data set and a test data, we look for the k most
similar trainin... |
def create_sql_table_from_df(df, name, conn):
'''
Args:
df, name, conn: Function takes in each dataframe
Returns:
table: Converts each dataframe to a sql table
'''
# Use try except
# it will try to make a table
# if a table exists the except part of the code will stop the p... |
def update():
x = open("db.txt", "r")
list1 = x.readlines()
list2 = []
for ele in list1:
list2 += ele.split()
for ele in list2:
if ele == "Name:" or ele == "Num:":
list2.remove(ele)
name = "name"
number = "number"
i = 1
phonebook = ... |
from tkinter import *
root = Tk()
root.title("First GUI")
content = ""
txt_input = StringVar(value="0" )
def btn(number):
global content
content = content+str(number)
txt_input.set(content)
def equal():
global content
calculate = float(eval(content))
txt_input.set(calculate)
... |
from tkinter import*
from tkinter import ttk, messagebox
class Register:
def __init__ (self,root):
self.root=root
self.root.title("REGISTRATION WINDOW")
self.root.geometry("1350x700+0+0")
frame1=Frame(self.root,bg="gray")
frame1.place(x=480,y=100,width=700,height=500... |
#!/usr/bin/env python3.0
#!-*coding:utf-8 -*-
#!@Time :2018-5-22 10:59
#!@Author : LYC
#!@File : Leecode_singleNumber_function2_.PY
class Solution(object):
"""
:type nums :list[int]
:rtype : int
"""
def singleNumber(self,nums):
num = 0
for p in nums:
num ^= p
retu... |
#!/usr/bin/env python3.0
#!-*coding:utf-8 -*-
#!@Time :2018-5-22 11:07
#!@Author : LYC
#!@File : Leecode_intersect_function1_.PY
class Solution(object):
def intersect(self, nums1, nums2):
list_interset = []
for p in nums1:
for k in nums2:
if p == k:
li... |
a=int(input("enter 1st number"))
one=a
b=int(input("enter 2nd number"))
two=b
def odd(one,two):
newlist = []
for i in range(one,two):
if i%2 !=0:
newlist.append(i)
print(newlist)
return newlist
odd(one,two)
#alternate way
def oddRange(num1, num2):
for i in range(num1+1, num2):
if i%2 != 0:
print(i)
... |
def changeString(p):
for i in range(len(p)):
if i=='a'or i=='e' or i=='i' or i=='o' or i=='u'
p.replace(i,upper(i))
x=print("enter string")
changeString(p)
|
'''raw_input = input('Enter the CSV : ')
str_list = [x for x in raw_input.split(",")]
str_list.sort()
#print(str_list)
print (','.join(str_list))'''
lines = []
print('Enter the input in multi lines : ')
while True:
test = input()
if test:
lines.append(test)
else:
break
print('\n'.join... |
x = 2
y = 7
z = 10
if x > y:
print(x,'is greater than y')
if x < y:
print(x,'is less than y')
if x==y:
print(x,'is equals to',y)
'''
cannot do this
if x < '2':
print(x,'is less than 2')
'''
if z > y > x:
print(z,'is greater than',y,'which is greater than',x)
###################################... |
#3! = 3*2*1
'''
fact_number = int(input('Enter the number : '))
factorial = 1
if fact_number < 0:
print('Fatorial for negative numbers not possible')
elif fact_number==1:
print('Factorial of 0 is 1')
else:
for i in range(1,fact_number+1):
factorial = factorial*i
#print(i)
print(factorial)
'''
... |
import urllib2
import requests
import pandas as pd
from bs4 import BeautifulSoup
import time
import sys
def get_wga_database():
"""
Download a CSV of the WGA collection.
** currently doesn't work
"""
url = 'http://www.wga.hu/database/download/data_txt.zip'
response = urllib2.urlopen(url)
# ... |
def add_all(nums):
ret_num = 0
for n in nums:
ret_num += n
return(ret_num)
# main
all_nums = [1,2,3,4,5,6,7,8,9,10]
sum_num = add_all(all_nums)
print("合計は、" + str(sum_num) + "です")
|
"""
@file: cci_10-5.py
@author: Taylor Curran
@brief: Solution to problem 10.5 from Cracking the Coding Interview
@version 0.1
@date 2020-07-01
@note McDowell, Gayle Lakkmann. Cracking the Coding Interview.
6th ed. Palo Alto, CA: CareerCup, 2016.
@copyright Copyright (c) 2020
"""
"""
Problem 10.5: "Sparse Search: ... |
# File: 01_03_new-year-chaos.py
# Name: Taylor Curran
# Date: September 22, 2020
# Description:
# HackerRank > Interview Preparation Kit > Arrays > New Year Chaos
"""
Problem: It's New Year's Day and everyone's in line for the Wonderland
rollercoaster ride! There are a number of people queued up, and each person
wea... |
"""
@file: cci_10-9.py
@author: Taylor Curran
@brief: Solution to problem 10.9 from Cracking the Coding Interview
@version 0.1
@date 2020-07-01
@note McDowell, Gayle Lakkmann. Cracking the Coding Interview.
6th ed. Palo Alto, CA: CareerCup, 2016.
@copyright Copyright (c) 2020
"""
"""
Problem 10.9: "Sorted Matrix S... |
from threading import Timer
class GorrabotTimer:
"""Call a function every specified number of seconds:
gt = GorrabotTimer(f, 1800)
gt.start()
gt.stop() # stop the timer's action
"""
def __init__(self, function, interval):
self._timer = None
self.f... |
import numpy as np
a = np.array([1, 2, 3]) # Tạo array 1 chiều
print(type(a)) # Prints "<class 'numpy.ndarray'>"
print(a.shape) # Prints "(3,)"
print(a[0], a[1], a[2]) # Prints "1 2 3"
a[0] = 5 # Thay đổi phần tử vị trí số 0
print(a) # Prints "[5, 2, 3]"
b = np.array([[1,2,3],[4,5,6]]) # Tạo array 2 chiều
print(b.shape... |
# A program that calculates BMI
name = input("What is Your Name: ")
hieght = float(input("Write Your height in Meters: "))
weight = float(input("Write Your weight in KG: "))
def bmi_calc(name, hieght, weight):
bmi = weight / (hieght**2)
if bmi < 20:
return "{0}, your BMI is {1:.3f} you're underweight... |
# Lists
pl = ["C","C++","Java","Go","Python"]
# Swap Python to C
temp = pl[0]
pl[0] = pl[4]
pl[4] = temp
# print(pl)
# Dictionary
userInfo = {
"Name":"Gorad",
"age":20,
"Study": True,
"Work": False,
"Email":"gorad@gmail.com"
}
# Classes
class Employee:
def __init__(self,name,age,email):... |
'''
Sets: Unordered collection of unique, immutable objects
'''
s = {112, 23, 34, 454, 56, 57, 676, 7878}
print(type(s))
d = {}
print(type(d))
# Empty set makes it dictionary so for empty use set
ss = set()
ss.add(12)
ss.add(12)
# Adding multiple items to sort
ss.update([123, 3434, 454, 56, 56, 55])
# Memebership and... |
from math import factorial
words = "I will watch the match after I take dinner".split()
# Modern
length = [len(word) for word in words]
print(length)
# Legacy
oldLength = []
for word in words:
oldLength.append(len(word))
print(oldLength)
# Modern
try:
f = [len(str(factorial(x))) for x in range(30)] # using l... |
"""
Tarea: día anterior
Autor: Juan Oablo Rubio
Fecha: 07/abr/21
Grupo: ESI-232
Profesor: Jorge A. Zaldívar Carrillo
Descripción: Calcula el dia anterior de una fecha dada.
"""
dia = int(input("Intodusca el numero del día: "))
mes = int(input("Intodusca el numero del mes: "))
año = int(input("Intodusca el n... |
from enum import Enum
from enum import IntEnum
class CronType(Enum):
"""The type of event in cron."""
off = 0
class PowerMode(IntEnum):
"""Power mode of the light."""
LAST = 0
NORMAL = 1
RGB = 2
HSV = 3
COLOR_FLOW = 4
MOONLIGHT = 5
class BulbType(Enum):
"""
The bulb's... |
# Y = c0 + c1x
class Line(object):
def __init__(self, c0, c1):
self.c0, self.c1 = c0, c1
def __call__(self,x):
print 'Line', self.c0 + self.c1*x
return self.c0 + self.c1*x
def table(self, L, R,n):
"""return a table with n points for L <= x <= R."""
s = ''
im... |
class Line:
def __init__(self,p1,p2):
self.p1, self.p2 = p1,p2
def value(self):
x0, y0 = self.p1[0], self.p1[1]
x1, y1 = self.p2[0], self.p2[1]
a = (y1 - y0)/float(x1-x0); b = y0*a*x0
return b
def test_Line():
comp = Line((1.5,3.4), (4,1.1)).value()
expect =... |
#formula:
#start with i=1 set i=i+2, repeat until i=n
n = 9
odd = 1
print odd
while odd < n-1:
odd = odd + 2
print odd
"""
Terminal>python odd.py
1
3
5
7
9
"""
|
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.preprocessing import PolynomialFeatures
from sklearn.metrics import mean_squared_error, r2_score
import matplotlib.pyplot as plt
x = 2 - 3 * np.random.normal(0, 1, 100)
... |
# Committing changes to github new
import math as m
print("Calculator Operations\n"
"1. Addition\n"
"2. Subtraction\n"
"3. Multiplication\n"
"4. Division\n"
"5. Square\n"
"6. Square Root\n"
"7. Sine\n"
"8. Cosine\n"
"9. Tangent\n"
"10.Log\n"
"11.Recipr... |
# Beginning Python (From Novice to Professional)
# Chapter 1
name = input("What is your name?")
print("Hello, " + name + "!")
# Page 14
input("Press <enter>") |
# Section CNN - Convert Images Into Tensors
# Author Jose Smith
# Start Date: 20210119
# End Date:
# Importing the relevant packages
print('=============Importing the relevant packages================================')
import numpy as np
from PIL import Image
import datetime
# programstart stores current time
progra... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# 插入排序
def insertion_sort(seq):
for i in range(1, len(seq)):
item = seq[i]
for j in range(i)[::-1]:
if item < seq[j]:
seq[j+1] = seq[j]
seq[j] = item
else:
break
return seq
... |
numList = (10,23,40,90)
print("numList values are : ",numList)
for num in numList:
if num % 5 == 0:
print(num)
|
# coding: utf-8
# In[1]:
import mpl_toolkits.mplot3d as mplt3d
import matplotlib.pyplot as plt
import scipy.integrate as scint
import math
import numpy as np
#%matplotlib inline
# In[ ]:
# In[19]:
def Getx(nx, xmin, xmax):
dx = abs(xmax-xmin)/float(nx)
x = np.arange(nx+1)*dx + xmin
return x
# I... |
#assign some boolean variables
a=True
b=False
print('a=',a,'b=',b)
#reassign a
a=False
print('a=',a,'b=',b)
|
#Get diividend and divisor from user
dividend,divisor=eval(input('Please enter the dividend and divisor: '))
#we want to divide only if divisor is not zero
#otherwise, we will print an error message
msg=dividend/divisor if divisor!=0 else 'Error: Cannot divide by zero '
print(msg)
|
import numpy as np
from matplotlib import pyplot as plt
import random
import math
##### Parameters
C = 2
N1,N2 = 3,C
randomWeightsRange = 1
alpha = 0.1
#####
## Setting the random seed for testing purposes
random.seed(6) ## This lets 2/3 neurons in the hidden layer have non-zero values after relu activation
## Debug... |
#!/usr/bin/env python3
set = [5, 2, 4, 6, 1, 3]
for j in range(1, len(set)):
key = set[j]
i = j - 1
while (i >= 0 and set[i] > key):
set[i+1] = set[i]
i = i - 1
set[i+1] = key
print(set)
|
n =str(input("Digite seu nome: "))
s = str(input("Digite sua senha: "))
while n==s:
print("Senha inválida")
n =str(input("Digite seu nome: "))
s = str(input("Digite sua senha: "))
print("Obrigado")
|
#!/bin/usr/env python
# MIT by Vitali
# Prints count of substring occurrences in a string
s = raw_input()
start=0
count=0
while start<=len(s):
n=s.find('b',start,len(s))
prnt=(s[start:start+3])
if prnt =='bob':
start=n+2
count+=1
else:
start+=1
print "Number of times bo... |
num1 = float(input("Ingrese el primer número: "))
operacion = input("Ingrese la operación matemática a realizar: ")
num2 = float(input("Ingrese el segundo número: "))
# Suma, Resta, Multiplicación, División
if operacion == "+":
print(num1 + num2)
elif operacion == "-":
print(num1 - num2)
elif operacion == "*":... |
from sklearn.model_selection import GridSearchCV, StratifiedKFold, \
RandomizedSearchCV
class ModelTunerCV:
def __init__(self, model, scorer, cv=3):
"""
Args:
model: sklearn model, Model the user wishes to tune
scorer: string or valid scorer, The scoring method to be use... |
# 获取mnist数据集
import matplotlib.pyplot as plt
from keras.datasets import mnist
(train_x, train_y), (test_x, test_y) = mnist.load_data()
print(train_x.shape, train_y.shape)
print(test_x.shape, test_y.shape)
# 可视化数据集
fig = plt.figure()
for i in range(15):
plt.subplot(3, 5, i+1)
plt.tight_layout()
plt.imshow(... |
"""
General drawing methods for graphs using Bokeh.
"""
import math
from bokeh.io import show, output_file
from bokeh.plotting import figure
from bokeh.models import (GraphRenderer, StaticLayoutProvider, Circle, Oval, LabelSet,
ColumnDataSource)
from bokeh.palettes import Spectral8
from graph... |
# f1 = open("test.txt", 'w')
# # f1.write("Life is too short")
# # f1.close()
# # f2 = open("test.txt", 'r')
# # print(f2.readline())
# f1 = open("test.txt", 'a')
# str= input("저장할 내용을 입력하세요.:") #, end=' '
# f1.write(str)
# f1.write("\n")
# f1.close()
#
# f = open("새파일.txt", 'r')
# while True:
# line = f.readline... |
class Solution:
def isValid(self, s: str) -> bool:
paren_list = list()
for i in range(len(s)):
if s[i] == '(' or s[i] == '{' or s[i] == '[':
paren_list.append(s[i])
elif (len(paren_list) != 0):
if s[i] == ')' ... |
def Largest(A, low_index, high_index):
if(len(A)==0):
return 0
max = 0
if(low_index == high_index):
return A[low_index]
else:
max = Largest(A, low_index +1, high_index)
if A[low_index] >= max:
return A[low_index]
else:
return max
lista = [1,6,7,2,8,10]
print(Largest(lista, ... |
class Num:
def __init__(self, value):
self.value = value
def eval(self):
return int(self.value)
class MulStr:
def __init__(self, value):
self.value = value
def eval(self):
return self.value * 5
|
#!/user/bin/python
#Accept two list from user and return the intersection of them
def intersectionTwoList(L1,L2):
L3=[]
i=0
j=0
while i<len(L1):
while j<len(L2):
if L1[i]==L2[j]:
if L1[i] not in L3:
L3.append(L1[i])
... |
#! /usr/bin/python
def CountBit(no):
count=0
x=1
while x<=no:
if (no & x)!=0:
count +=1
x=x<<1
return count
def main():
no=eval(input("Enter Number to count number of Bits:"))
output=CountBit(no)
print("{} Number of one bits in {}" .format(output,n... |
#!/user/bin/python
#Pattern 5:
# *
# ***
# *****
#*******
#*******
# *****
# ***
# *
def pattern5(no):
for i in range(1,no+1):
for j in range (1,no-i+1):
print('\t',end='')
for k in range (1,i+1):
print ('*\t',end='')
for l in range (1,i)... |
#!/user/bin/python
#WAP :Accept number from user and define a function Sum of cubes of digit
def sumOfCubes (no):
sum=0
while no!=0:
rem=no%10
sum=(rem*rem*rem)+sum
no=no//10
print(sum)
def main():
no=eval(input("Enter Number to obtain Sum of cubes of digit:"))
... |
#!/user/bin/python
# Program: Print below pattern
# *
# **
# ***
# ****
def pattern1(no):
for i in range(1,no+1):
for j in range(1,i+1):
print ('*\t',end='')
print ("\n")
def main():
no=eval(input("Enter Number to for pattern1:"))
pattern1(no)
if ... |
#!/user/bin/python
def variableArgsAdd(*args):
sum=0
print(type(args))
for x in args:
sum+=x
print(sum)
variableArgsAdd(10,20,30,40,50,60,70)
variableArgsAdd(1,2,3,4,5,6,7,8) |
#!/user/bin/python
def CompareTwoList(L1,L2):
if type(L1)!= list or type(L2) != list:
print ("L1 is not list")
return
if len(L1)!=len(L2):
return 0
L1.sort();L2.sort()
for i in range(len(L1)):
if L1[i]==L2[i]:
continue
break
else:
... |
import numpy as np
import random
# Times to run
epoch = 10000
# There are 2 inputs
inputLayerSize = 2
# NN nodes
hiddenLayerSize = 3
# Only one output
outputLayerSize = 1
# Learning rate
L = 0.1
# There are 2 inputs for XOR
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
# The truth table of XOR
# ANN just can le... |
#4. Create a list of thousand number using range and xrange and see the difference between each other.
"""
x-range is used on python 2 which shows the whole result as type list where as range
# is used on python 3 which does not show the whole result and type is range
""" |
# 5. Write a program to complete the task given below:
# Ask the user to enter any 2 numbers in between 1-10 and add both of them to another variable call z.
# Use z for adding 30 into it and print the final result by using variable result.
x = int (input("Enter 1st number between 1 to 10: "))
y = int (input("Ent... |
# 8 If one data type value is assigned to ‘a’ variable and then a different data type value is assigned to ‘a’ again.
#Will it change the value. If Yes then Why?
#Value will change assigned to “a” even if they are a different data type because python automatically takes
# care of the physical representation for th... |
# 6 What is the output of the following code examples?
x=123
for i in x:
print(i)
#int obj is not iterable(error)
i = 0
while i < 5:
print(i)
i += 1
if i == 3:
break
else:
print('error')
#output: 0,1,2
count = 0
while True:
print(count)
count += 1
if cou... |
# Assignment-1
# TASK ONE: NUMBERS AND VARIABLES
# 1.Create three variables in a single line and assign different values to them and
# make sure their data types are different. Like one is int, another one is float and the last one is a string.
a, b, c = 10, 15.5, 'Welcome to Consult add' |
veta = "Cez vikend je planovana odstavka tunela pod hradom".split()
print(f'Veta pozostava z {len(veta)} slov.')
nova_veta = ""
for slovo in veta:
nova_veta += slovo[0].upper() + slovo[1:]
print(nova_veta)
uplne_nova_veta = ""
for pismeno in nova_veta:
if pismeno.isupper():
uplne_nova_veta += ' '
... |
rawdata = []
required_fields = ["byr","iyr","eyr","hgt","hcl","ecl","pid"]
with open("input.txt","r") as file:
num = 1
rawdata = file.read().split("\n\n")
#print(rawdata)
def valid(item):
for field in required_fields:
if field not in item:
return False
return True... |
import re
def get_policy_info(key):
dash = key.find("-")
minimum = int(key[:dash])
maximum = int(key[dash+1:-2])
char = key[-1]
return [minimum,maximum,char]
def meets_policy(value,minimum,maximum,char):
if len(re.findall(char,value)) >= minimum and len(re.findall(char,value)) <= max... |
#1. Write a program in Python to perform the following operation:
# If a number is divisible by 3 it should print “Consultadd” as a string
# If a number is divisible by 5 it should print “Python Training” as a string
# If a number is divisible by both 3 and 5 it should print “Consultadd Python Training” as a string.
x... |
##############WEEKEND ACTIVITY- THEORETICAL JOURNEY########################################
# 1.What is Pickling and Unpickling in Python? Explain with the help of example.
### pickling and unpickling powerful algorithm for serializing and de-serializing a
# Python object structure.
dict_obj = {1:"Se... |
a= 1+2j
b=10
c=5
temp=a,b
a=c
b=c
print ('after swapping: {}' .format(a))
print ('after swapping: {}' .format(b)) |
#!/usr/bin/env python
__author__ = "Rafael Caballero"
# Problem: Given an array of integers,
# return a new array such that each element
# at index i of the new array is the product
# of all the numbers in the original array
# except the one at i.
# Example1: if our input was [1, 2, 3, 4, 5],
# the expecte... |
s = 'azcbobobegghakl'
size = len(s)
string1 = s[0]
largest = ""
for i in range(len(s)-1):
if s[(i+1)] >= s[i]:
string1 = string1 + s[(i+1)]
else:
if len(string1) > len(largest):
largest = string1
string1 = s[i+1]
else:
string1 = s[i+1]
if len(string1) ... |
import os
def align(s,w):
if len(s) > w:
return s
else:
spaces = (w - len(s))//2
result = " " * spaces + s
return result
w = os.get_terminal_size().columns
s = input('Please input a string:')
print(len(s))
print (align(s,w))
#print('hello world'.center(width))
#print("{:>12}".... |
score = input("Please enter score:")
try:
score=float(score)
except:
print("Error, score must be numeric")
quit()
if score < 0 or score > 1:
print("Error,score must be between 0 and 1:")
quit()
if score >= .9:
grade = "A"
elif score >= .8:
grade = "B"
elif score >= .7:
grade = "C"
elif s... |
fname=input("Enter file name:")
if len(fname)< 1:
fname= "mbox-short.txt"
fh = open(fname)
count = 0
largest = None
counts=dict()
namelist=list()
for line in fh:
line = line.rstrip()
if line.startswith('From:'):
countlist=list(line.split(" "))
namelist.append(countlist[1])
count = co... |
balance = 320000
int_rate = 0.2
monthly_int_rate = int_rate/12
monthly_pmt_lb = balance/12
monthly_pmt_ub = (balance * (1 + monthly_int_rate)**12)/12
originalbalance = balance
while abs(balance) > .02:
balance = originalbalance
payment = (monthly_pmt_ub - monthly_pmt_lb)/2 + monthly_pmt_lb
for month in rang... |
x = input('Please input string:')
s = len(x)
l = x[ ::-1]
r = -s
count = 0
while s > 0:
if x[(-r-s)] == l[(0-s)]:
count = count+1
else:
print('The string is not a palindrome.')
break
s -= 1
if count == len(x):
print('The string is a palindrome.')
|
import copy
def comma(list):
#Function takes a list and returns a string with items separated by a comma and a space (', '),
# with ('and ') inserted before the last item
if len(list) == 0:
return list
else:
editedList = []
for i in list:
if len(list) != list.index(i... |
#! python3
# ProjectEUler.net Problem 2
def fibonacci():
sequence = [1,2]
while (sequence[-1] + sequence[-2]) < 4000000:
sequence.append(sequence[-1] + sequence[-2])
print(sequence[-1])
return sequence
fibfourmillion = fibonacci()
evenFibNumbers = []
for i in fibfourmillion:
if i % 2 == 0:
print(i)
even... |
import sys
from colorama import Fore, Style, init #colorama required for easily displaying colored text
import random
init() # initialises colorama for windows
# collatz sequence takes any integer and works its way to one, using only two operations:
# if the integer if even it is divided by two
# if the integer is odd... |
#! python3
from pathlib import Path
import pprint as pp
import pyinputplus as pyip
workingDirectory = Path.cwd()
def findkeyword(searchterm, glob, directory):
files = {}
directory = Path(directory)
for file in list(directory.glob(str(glob))):
currentFile = open(file, "r")
lineIndex = 0
... |
"""
dai o que preciso fazer:
1. tirar os timestamps (ja fiz!)
2. tirar os simbolos (ja fiz)
3. selecionar so as linhas que tem C: no comeco
4. dessas linhas, contar as palavras de cada linha
5. fazer isso pra todos os textos numa pasta
"""
import nltk
from nltk.tokenize import word_tokenize
import string
import re
n... |
import os
# -----Euler Problem 1-----
# Work out the first ten digits of the sum of the following one-hundred 50-digit numbers (data/euler13_data.txt)
os.chdir(str(os.getcwd()))
with open("data/euler13_data.txt", 'r') as f:
lines = f.readlines()
s = 0
for x in range(0, len(lines)):
lines[x] = int(lines[x])... |
from IPython.display import clear_output, display
import random
def display_board(board):
clear_output()
print(board[7] + '|' + board[8] + '|' + board[9])
print('-----')
print(board[4] + '|' + board[5] + '|' + board[6])
print('-----')
print(board[1] + '|' + board[2] + '|' + board[3])
def pla... |
# coding:utf-8
## 字符串类型
#无需转义,直接打印字符串
print(r'\\\\\\tttt\\\\')
# 打印普通字符串
print('abc"')
print("abc'")
print("abc\"")
print('abc\'')
#打印多行字符串,包括换行符
print('''line1
line2
line3''')
## boolean 类型
print(3>2)
if not 1>2:
print("1>2 is false")
# 算法运算符
print(10/3)
print(10//3)
print(10%3)
# 编码问题
# 计算机中都是以unicode编... |
import sys
def distanceCalc (x , y):
return x*y
def speedCalc (x , y):
return x/y
def timeCalc (x , y):
return x/y
def calc_mins(x):
x.strip(" ")
if x.find("h")>0:
formattedHours = x.strip("h")
return float(formattedHours)
elif x.find("m")>0:
formattedMins = x.strip("m")
... |
#!/usr/bin/python3
"""[a class MyInt that inherits from int]
"""
class MyInt(int):
"""[summary]
Arguments:
int {[class]} -- [inheritance class]
Returns:
[bool] -- [MyInt is a rebel. MyInt has == and != operators inverted]
"""
pass
def __eq__(self, other):
"""[it's a ... |
#!/usr/bin/python3
def print_square(size):
"""[unction that prints a square with the character #]
Arguments:
size {[int]} -- [the size length of the square]
Raises:
TypeError: [size must be an integer]
ValueError: [size must be >= 0]
"""
if type(size) != int:
raise... |
#!/usr/bin/python3
def square_matrix_simple(matrix=[]):
sq = []
for elm in matrix[:]:
sq.append(list(map(lambda x: x ** 2, elm)))
return sq
|
#!/usr/bin/python3
"""[function that appends a string at the end of a text file]
"""
def append_write(filename="", text=""):
"""
Keyword Arguments:
filename {str} -- [file path] (default: {""})
text {str} -- [text to add to the file] (default: {""})
Returns:
[int] -- [the numb... |
import threading
class BankAccount(object):
def __init__(self):
self.balance = 0
self.actived = True
self._value_lock = threading.Lock()
def get_balance(self):
with self._value_lock:
if self.actived:
return self.balance
else:
... |
x=5
while (x>=1):
print(x)
x=x-1
|
sentence=input("give me a sentence")
number_words=0
for letter in sentence:
if letter==" ":
number_words=number_words+1
print("there are",number_words+1,"words") |
# This script is used to help me create the world generation algorithm.
# It's included for anyone curious as to how it works, feel free to use any
# parts of the algorithm!
# Uses https://imgur.com/a/EoXWh as a reference, credit to the tModLoader team!
from PIL import Image
import matplotlib.pyplot as mpplot
from enu... |
# defining my functions before starting the base program
#I prefer integers to floats as they don't take up as much space as floats. Though I will use floats in this.
def getFloat(prompt):
while True:
x= float(input(prompt))
return x
def getOperator ():
while True:
operator= input("Wh... |
from sys import argv
script, nome_usuario = argv
prompt = '> '
print("Olá %s, Eu sou o %s script." % (nome_usuario, script))
print("Eu gostaria de lhe fazer algumas perguntas.")
voce_gosta = input("%s, você gosta de mim? " % nome_usuario)
onde_mora = input("Onde você mora, %s? " % nome_usuario)
computador = input("Qu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.