Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

四捨五入

# Hello World program in Python
import sys
import math
print(sys.version);

def xround(v,p):
  return math.ceil(v*pow(10,p))/pow(10,p);


bb=2.605;  print(xround(bb,2),round(bb,2));
bb=2.615;  print(xround(bb,2),round(bb,2));
bb=2.625;  print(xround(bb,2),round(bb,2));
bb=2.635;  print(xround(bb,2),round(bb,2));
bb=2.645;  print(xround(bb,2),round(bb,2));
bb=2.655;  print(xround(bb,2),round(bb,2));
bb=2.665;  print(xround(bb,2),round(bb,2));
bb=2.675;  print(xround(bb,2),round(bb,2));
bb=2.685;  print(xround(bb,2),round(bb,2));
bb=2.695;  print(xround(bb,2),round(bb,2));
bb=3.605;  print(xround(bb,2),round(bb,2));
bb=3.615;  print(xround(bb,2),round(bb,2));
bb=3.625;  print(xround(bb,2),round(bb,2));
bb=3.635;  print(xround(bb,2),round(bb,2));
bb=3.645;  print(xround(bb,2),round(bb,2));
bb=3.655;  print(xround(bb,2),round(bb,2));
bb=3.665;  print(xround(bb,2),round(bb,2));
bb=3.675;  print(xround(bb,2),round(bb,2));
bb=3.685;  print(xround(bb,2),round(bb,2));
bb=3.695;  print(xround(bb,2),round(bb,2));

Execute Python-3 Online

#prime number generator

import math

def is_prime(n):
    if n == 1:
        return False
        
    if n == 2:
        return True
        
    if n > 2 and n % 2 == 0:
        return False
        
    for i in range(2, n):
        if n % i == 0:
            return False
    
    return True
        
  
  
for y in range (1, 100000):
    if is_prime(y) == True:
        print (y)

Primjer 11

# primjer pokazuje mogućnost uspoređivanja n-torki

# inicijalizacija n-torki
T1 = (1, 7, 8)
T2 = (2, 5, 6)

# usporedba n-torki, uspoređuje se prvi član
print(T1, T2)
print (T1 < T2)
print('----------')

# inicijalizacija n-torki
T3 = (2, 7, 8)
T4 = (2, 5, 6)

# usporedba n-torki, 
# ako je prvi član isti uspoređuje se drugi član
print(T3, T4)
print (T3 < T4)
print('----------')

# usporedba n-torki sa različitim brojem članova 
T5 = (2, 2, 2)
T6 = (2, 2, 2, 2)
print(T5, T6)
print(T5 == T6)
print(T5 < T6)

pandas Foundations-Chapter 1

df.head(3)   # 檢視前3列,預設5列
df.tail(3)   # 檢視末3列,預設5列

df.info()   # DataFrame 基本資料
'''
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 13374 entries, 0 to 13373
Data columns (total 5 columns):
CountryName                      13374 non-null object
CountryCode                      13374 non-null object
Year                             13374 non-null int64
Total Population                 9914 non-null float64
Urban population (% of total)    13374 non-null float64
dtypes: float64(2), int64(1), object(2)
memory usage: 522.5+ KB
'''

''' NumPy and pandas working together '''

# Import numpy
import numpy as np

print(df)
'''
      Total Population
Year                  
1960      3.034971e+09
...
2010      6.924283e+09
'''

# Create array of DataFrame values: np_vals
np_vals = df.values    # df.values 屬性:建立 numpy array
'''
[[3.03497056e+09]
 ...
 [6.92428294e+09]]
'''

# =============================================================================
# Building DataFrames from scratch
# =============================================================================

''' Zip lists to build a DataFrame '''

print(list_keys)    # ['Country', 'Total']
print(list_values)  # [['United States', 'Soviet Union', 'United Kingdom'], [1118, 473, 273]]

# Zip the 2 lists together into one list of (key,value) tuples: zipped
zipped = list(zip(list_keys, list_values))  # [('Country', ['United States', 'Soviet Union', 'United Kingdom']), ('Total', [1118, 473, 273])]

# Build a dictionary with the zipped list: data
data = dict(zipped) # {'Country': ['United States', 'Soviet Union', 'United Kingdom'], 'Total': [1118, 473, 273]}

# Build and inspect a DataFrame from the dictionary: df
df = pd.DataFrame(data)
print(df)
'''
          Country  Total
0   United States   1118
1    Soviet Union    473
2  United Kingdom    273
'''

# 重新命名欄位
df.columns = ["國家", "總數"]

''' Broadcasting '''

# Broadcast = 設定所有資料的某個欄位值

print(cities)   # 賓州的城市 ['Manheim', ..., 'Great bend']

# Make a string with the value 'PA': state
state = "PA"

# Construct a dictionary: data
data = {'state':state, 'city':cities}

# Construct a DataFrame from dictionary data: df
df = pd.DataFrame(data)

# Print the DataFrame
print(df)
'''
   state             city
0     PA          Manheim
1     PA     Preston park
...
14    PA       Great bend
'''

# =============================================================================
# Importing & exporting data
# =============================================================================

''' Reading a flat file '''

# given a csv file "data_file"

# Create a list of the new column labels: new_labels
new_labels = ['year', 'population']

# Read in the file, specifying the header and names parameters: df2
# header = 1:須去除標題列
# names: 設定欄位名稱
df = pd.read_csv(data_file, header=0, names=new_labels)

''' Delimiters, headers, and extensions '''

# given a flat file "file_messy", which has multiple header lines, comment records (rows) interleaved throughout the data rows, and space delimiters instead of commas

# Read the raw file as-is: df1
df1 = pd.read_csv(file_messy)

# Print the output of df1.head()
print(df1.head())
'''
                                                   The following stock data was collect on 2016-AUG-25 from an unknown source
These kind of comments are not very useful                                                  are they?                        
Probably should just throw this line away too          but not the next since those are column labels                        
name Jan Feb Mar Apr May Jun Jul Aug Sep Oct No...                                                NaN                        
# So that line you just read has all the column...                                                NaN                        
IBM 156.08 160.01 159.81 165.22 172.25 167.15 1...                                                NaN                        
'''

# Read in the file with the correct parameters: df2
df2 = pd.read_csv(file_messy, delimiter=" ", header=3, comment="#")

# Print the output of df2.head()
print(df2.head())
'''
     name     Jan     Feb     Mar     Apr  ...     Aug     Sep     Oct     Nov     Dec
0     IBM  156.08  160.01  159.81  165.22  ...  152.77  145.36  146.11  137.21  137.96
1    MSFT   45.51   43.08   42.13   43.47  ...   45.51   43.56   48.70   53.88   55.40
2  GOOGLE  512.42  537.99  559.72  540.50  ...  636.84  617.93  663.59  735.39  755.35
3   APPLE  110.64  125.43  125.97  127.29  ...  113.39  112.80  113.36  118.16  111.73
'''

# Save the cleaned up DataFrame to a CSV file without the index
df2.to_csv(file_clean, index=False)

# Save the cleaned up DataFrame to an excel file without the index
df2.to_excel('file_clean.xlsx', index=False)

# =============================================================================
# Ploting with pandas
# =============================================================================

suitabletitle

def search(a,k):
    for i in range(0,len(a)):
        if(a[i]==k):
            return 1
    return 0

def bs(a,k):
    mp=len(a)//2
    f=a[0:mp]
    s=a[mp:len(a)]
    
    if search(a,k)==0:
        return "false"
    else:
        if a[mp]==k:
            return mp
        else:
            if a[mp]>k:
                return bs(a[0:mp],k)
            else:
                if a[mp]<k:
                    return bs(a[mp:len(a)],k)+mp
    return bs(a,k)

a=[3,8,13,16,25,31,49,100]
k=31
print(bs(a,k))

境外访问测试

import urllib.request
with urllib.request.urlopen('https://www.google.com/') as f:
    print(f.read(10))
print("*"*80)
with urllib.request.urlopen('https://cn.nikkei.com/') as f:
    print(f.read(10))

Convert to Celsius

# Hello World program in Python
    
def convert_to_celsius(fahrenheit):
    
    '''(number) -> float
    
    Return the number of Celsius degrees equivalent to fahrenheit degrees.
    
    >>> convert_to_celsius(32)
    0.0
    >>> convert_to_celsius(212)
    100.o
    '''
    return (fahrenheit - 32) * 5/9
    
    
celsius = convert_to_celsius(32)
print (celsius)

print (convert_to_celsius(212))


fahrenheit = input("enter something")

useful link

# https://blog.gainlo.co/index.php/2016/05/24/design-a-recommendation-system/

# https://github.com/ShuaiW/data-science-question-answer

# https://www.huxiu.com/article/175046.html

shuttttpee

# Hello World program in Python
    
print ("Hello World!");

Execute Python-3 Online

import time
millis = int(round(time.time() * 1000))
result=1
for z in range(1):
    for x in range(100000):
        result = 1
        for y in range(130):
            result *= (y+1)*4
print(int(round(time.time() * 1000))-millis)
print(result)

Previous 1 ... 3 4 5 6 7 8 9 ... 204 Next
Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.