Rabu, 06 Mei 2020

Python Kursus Hari 3

Kursus LP2MARAY HARI3

ARRAY - LIST - TUPLE - DATAFRAME - DICTIONARY

In [130]:
#Array = satuan variabel dengan tipe sama
def binarySearch (arr, l, r, x): 
    if r >= l: 
        mid = l + (r - l)//2
        if arr[mid] == x: 
            return mid 
        elif arr[mid] > x: 
            return binarySearch(arr, l, mid-1, x)   
        else: 
            return binarySearch(arr, mid+1, r, x) 
  
    else: 
        return -1
  
# Test array 
arr = [ 2, 3, 4, 10, 40 ] 
x = 10
result = binarySearch(arr, 0, len(arr)-1, x) 
  
if result != -1: 
    print ("Element is present at index "+ str(result)) 
else: 
    print ("Element is not present in array")

    
###################
def bubbleSort(arr): 
    n = len(arr) 
    for i in range(n-1): 
        for j in range(0, n-i-1): 
            if arr[j] > arr[j+1] : 
                arr[j], arr[j+1] = arr[j+1], arr[j] 
                
arr = [64, 34, 25, 12, 22, 11, 90] 
bubbleSort(arr) 
  
print ("Sorted array :") 
for i in range(len(arr)): 
    print ("%d" %arr[i]),  

###########################
print ("largest array :") 
def largest(arr,n): 
    max = arr[0] 
    for i in range(1, n): 
        if arr[i] > max: 
            max = arr[i] 
    return max
  
arr = [10, 324, 45, 90, 45] 
n = len(arr) 
Ans = largest(arr,n) 
print ("Largest in given array is",Ans) 
print ("Sum array ", sum(arr))
  
###########################    
def leftRotate(arr, d, n): 
    for i in range(d): 
        leftRotatebyOne(arr, n) 
        
def leftRotatebyOne(arr, n): 
    temp = arr[0] 
    for i in range(n-1): 
        arr[i] = arr[i+1] 
    arr[n-1] = temp 
          
def printArray(arr,size): 
    for i in range(size): 
        print ("%d"% arr[i],end=" ") 
  
   
arr = [1, 2, 3, 4, 5, 6, 7,8,9,10,11,12,13] 
leftRotate(arr, 2, 7) 
printArray(arr, 7) 
Element is present at index 3
Sorted array :
11
12
22
25
34
64
90
largest array :
Largest in given array is 324
Sum array  514
3 4 5 6 7 1 2 
In [112]:
AL = list(range(21))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-112-6b616f512782> in <module>
----> 1 AL = list(range(21))

TypeError: 'list' object is not callable
In [113]:
#List = array dengan multi tipe data
my_list1=[]  # membuat lkist kosong
my_list2=["Apel","Belimbing",5,3.14,'q']
my_list3= ["LP2M", [8, 4, 6],[2, 0, 1, 5], ['a'],"ARRAY",'q',3.14]  # nested list

print(my_list2[0])
print(my_list2[2])
print(my_list2[4])

print(my_list3[0])
print(my_list3[3])
print(my_list3[1][2])
print(my_list3[2])

print(my_list3[-1])
print(my_list3[-4])

print("+++++++++++++++++++++++++++++++++++++++++++++++++");

#SLICE
print(my_list3[2:5])
print(my_list3[:-5])
print(my_list3[5:]) # elements 6th to end
print(my_list3[:])# elements beginning to end
print(my_list3) #ALL

print("+++++++++++++++++++++++++++++++++++++++++++++++++");

#SET
my_list3[0] = 1            
print(my_list3)

my_list3[1:4] = [411, 212, 667]  
print(my_list3)



print("+++++++++++++++++++++++++++++++++++++++++++++++++");

#EXPAND
my_list3 = [1, 3, 5]
print(my_list3)
my_list3.append(7)
print(my_list3)
my_list3.extend([9, 11, 13])
print(my_list3)

print("+++++++++++++++++++++++++++++++++++++++++++++++++");

#INSERTT
my_list3.insert(1,3)
print(my_list3)
my_list3[2:2] = [411, 212]
print(my_list3)

print("+++++++++++++++++++++++++++++++++++++++++++++++++");

#INSERT
del my_list3[4]
print(my_list3)

del my_list3[1:5]
print(my_list3)

del my_list3 # delete entire list
#print(my_list3)# Error: COZ  List not defined


print("+++++++++++++++++++++++++++++++++++++++++++++++++");

#PUSH POP
my_list = ['p','A','Q','p','l','e','m']
my_list.remove('p')

print(my_list)
print(my_list.pop(1)) #AMBIL index1= 'Q'
print(my_list)

print(my_list.pop()) #m /ambil yg paling kanan
print(my_list)    #['A', 'p', 'l', 'e']


my_list[2:4] = []   #['A', 'p']
print(my_list)       #[]

my_list.clear()    #Kosongkan LIST
print(my_list)       #[]


print("+++++++++++++++++++++++++++++++++++++++++++++++++");
#PROPERTIES
my_list = [3, 8, 1, 6, 0, 8, 4]
print(my_list.index(6)) #6 ada pada posisi ke-3   
print(my_list.count(8)) #8 ada 2
my_list.sort()     #[0, 1, 3, 4, 6, 8, 8]
print(my_list)
my_list.reverse() #[8, 8, 6, 4, 3, 1, 0]
print(my_list) 

for data in my_list:
    print("I like - ",data)

pow2 = []
for x in range(10):
    gabList=str(x)+"."+str(2 ** x)
    pow2.append(gabList)

for data in pow2:
    print("Incr ",data)
    
print(8 in my_list)#True
print('a' in my_list) # Output: False

print("+++++++++++++++++++++++++++++++++++++++++++++++++");
#LOOP

def count(list):
    item_count = 0
    for item in list[:]:
        item_count += 1
    return item_count

print("FUNGSI")
L = list(range(21))
print(count(L))
print(max(L))
print(min(L))
print(sorted(L))

print(list("abc")) #String to List
print(any(L))
print(all(L))
print(len(L))

jd=len(my_list)
for i in my_list:
    print(i)
print("WHILE")    
m=0
while m<jd:
    print(my_list[m])
    m=m+1
    
print("LooP")    
for i in [1,2,3]:
         if i%2==0:
                print(f"{i} is composite\n")
      
    
print("+++++++++++++++++++++++++++++++++++++++++++++++++");
#AKSES
A=[[[1,2],[3,4],5],[6,7]]
print(A[0]) #[[1, 2], [3, 4], 5]
print(A[0][1]) #[3,4]
print(A[0][1][1]) #4


a,b=[3,1,2],[5,4,6]
c=a+b
print(c)
a*=3
print(a)
Apel
5
q
LP2M
['a']
6
[2, 0, 1, 5]
3.14
['a']
+++++++++++++++++++++++++++++++++++++++++++++++++
[[2, 0, 1, 5], ['a'], 'ARRAY']
['LP2M', [8, 4, 6]]
['q', 3.14]
['LP2M', [8, 4, 6], [2, 0, 1, 5], ['a'], 'ARRAY', 'q', 3.14]
['LP2M', [8, 4, 6], [2, 0, 1, 5], ['a'], 'ARRAY', 'q', 3.14]
+++++++++++++++++++++++++++++++++++++++++++++++++
[1, [8, 4, 6], [2, 0, 1, 5], ['a'], 'ARRAY', 'q', 3.14]
[1, 411, 212, 667, 'ARRAY', 'q', 3.14]
+++++++++++++++++++++++++++++++++++++++++++++++++
[1, 3, 5]
[1, 3, 5, 7]
[1, 3, 5, 7, 9, 11, 13]
+++++++++++++++++++++++++++++++++++++++++++++++++
[1, 3, 3, 5, 7, 9, 11, 13]
[1, 3, 411, 212, 3, 5, 7, 9, 11, 13]
+++++++++++++++++++++++++++++++++++++++++++++++++
[1, 3, 411, 212, 5, 7, 9, 11, 13]
[1, 7, 9, 11, 13]
+++++++++++++++++++++++++++++++++++++++++++++++++
['A', 'Q', 'p', 'l', 'e', 'm']
Q
['A', 'p', 'l', 'e', 'm']
m
['A', 'p', 'l', 'e']
['A', 'p']
[]
+++++++++++++++++++++++++++++++++++++++++++++++++
3
2
[0, 1, 3, 4, 6, 8, 8]
[8, 8, 6, 4, 3, 1, 0]
I like -  8
I like -  8
I like -  6
I like -  4
I like -  3
I like -  1
I like -  0
Incr  0.1
Incr  1.2
Incr  2.4
Incr  3.8
Incr  4.16
Incr  5.32
Incr  6.64
Incr  7.128
Incr  8.256
Incr  9.512
True
False
+++++++++++++++++++++++++++++++++++++++++++++++++
FUNGSI
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-113-0a8545fbdc3d> in <module>
    122 
    123 print("FUNGSI")
--> 124 L = list(range(21))
    125 print(count(L))
    126 print(max(L))

TypeError: 'list' object is not callable
In [114]:
def search(list,n): 
    for i in range(len(list)): 
        if list[i] == n: 
            return True
    return False
  
list = [1, 2, 'sachin', 4,'Geeks', 6] 
  
n = 'Geeks'
  
if search(list, n): 
    print("Found") 
else: 
    print("Not Found") 
    
    
Found
In [139]:
#Tuple =array dengan muti tipe data dan statis (tidak bisa diubah)
nilai1 = (100,90,"Lulus")
nilai2= 100,90,"LULUS"
tups = [("Heru", 90), ("Riadi", 98), ("Tony", 89),("Nico", 85), ("Susan", 95), ("Adam", 80)] 

print(nilai1)
print(nilai2)
print(tups)

#List to Tuple
list1 = [1, 2, 5, 6] 
res = [(val, pow(val, 3)) for val in list1] 
print(res) 

#Touple to List
out = [item for t in tups for item in t] 
print(out)

result = []   
for t in tups: 
    for x in t: 
        result.append(x) 
        
print(result) 


def search(Tuple, n): 
    for i in range(len(Tuple)): 
        if Tuple[i] == n: 
            return True
    return False
  
Tuple= (1, 2, 'sachin', 4, 'Geeks', 6) 
n = 'Geeks'  
if search(Tuple, n): 
    print("Found") 
else: 
    print("Not Found") 

##############################SORT    

def Convert(tup, di): 
    for a, b in tup: 
        di.setdefault(a, []).append(b) 
    return di 
      

print(tups)
dictionary = {} 
print (Convert(tups, dictionary))     

##############################SORT
def Sort_Tuple(tup):  
    lst = len(tup)  
    for i in range(0, lst):            
        for j in range(0, lst-i-1):  
            if (tup[j][1] > tup[j + 1][1]):  
                temp = tup[j]  
                tup[j]= tup[j + 1]  
                tup[j + 1]= temp  
    return tup  
     
print(Sort_Tuple(tups))  

##############################Remove
def Remove(tuples): 
    tuples = [t for t in tuples if t] 
    return tuples 
tuples = [(), ('ram','15','8'), (), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('',''),()]  #Lost Empty
print(Remove(tuples)) 
(100, 90, 'Lulus')
(100, 90, 'LULUS')
[('Heru', 90), ('Riadi', 98), ('Tony', 89), ('Nico', 85), ('Susan', 95), ('Adam', 80)]
[(1, 1), (2, 8), (5, 125), (6, 216)]
['Heru', 90, 'Riadi', 98, 'Tony', 89, 'Nico', 85, 'Susan', 95, 'Adam', 80]
['Heru', 90, 'Riadi', 98, 'Tony', 89, 'Nico', 85, 'Susan', 95, 'Adam', 80]
Found
[('Heru', 90), ('Riadi', 98), ('Tony', 89), ('Nico', 85), ('Susan', 95), ('Adam', 80)]
{'Heru': [90], 'Riadi': [98], 'Tony': [89], 'Nico': [85], 'Susan': [95], 'Adam': [80]}
[('Adam', 80), ('Nico', 85), ('Tony', 89), ('Heru', 90), ('Susan', 95), ('Riadi', 98)]
[('ram', '15', '8'), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('', '')]
In [140]:
test_dict = {'Gfg' : 1, 'for' : 2, 'CS' : 3} 
print("The original dictionary is : " + str(test_dict)) 
  
val = 3
for key in test_dict: 
    if test_dict[key] == val: 
        res = key 
        
print("The key correspoding to value : " + str(res)) 
The original dictionary is : {'Gfg': 1, 'for': 2, 'CS': 3}
The key correspoding to value : CS
In [153]:
import random as rn 
  
dict = {} 
x, y, z = 10, 20, 30
dict[x, y, z] = x + y - z; 
  
x, y, z = 5, 2, 4
dict[x, y, z] = x + y - z; 
  
print(dict) 
#################################
places = {("-6.353359", "106.833121"):"lp2maray",("-6.352950", "106.833030"):"araycomp"} 
  
print(places) 
print('\n') 
  
lat = [] 
long = [] 
plc = [] 
for i in places: 
    lat.append(i[0]) 
    long.append(i[1]) 
    plc.append(places[i[0], i[1]]) 
    
print(lat) 
print(long) 
print(plc) 


def returnSum(myDict):       
    sum = 0
    for i in myDict: 
        sum = sum + myDict[i]       
    return sum
  
dict = {'a': 100, 'b':200, 'c':300} 
print("Sum :", returnSum(dict)) 

print ("Data is : " + str(dict)) 
del dict['a'] 
print ("Hasil : " + str(dict)) 
del dict['c']
print ("Hasil : " + str(dict)) 

######################################Convert
def Convert(tup, di): 
    for a, b in tup: 
        di.setdefault(a, []).append(b) 
    return di 
      
tups = [("akash", 10), ("gaurav", 12), ("anand", 14), ("suraj", 20), ("akhil", 25), ("ashish", 30)] 
dictionary = {} 
print (Convert(tups, dictionary)) 
{(10, 20, 30): 0, (5, 2, 4): 3}
{('-6.353359', '106.833121'): 'lp2maray', ('-6.352950', '106.833030'): 'araycomp'}


['-6.353359', '-6.352950']
['106.833121', '106.833030']
['lp2maray', 'araycomp']
Sum : 600
Data is : {'a': 100, 'b': 200, 'c': 300}
Hasil : {'b': 200, 'c': 300}
Hasil : {'b': 200}
{'akash': [10], 'gaurav': [12], 'anand': [14], 'suraj': [20], 'akhil': [25], 'ashish': [30]}
In [ ]: