[codecademy] 5.LISTS & DICTIONARIES

Posted by 알 수 없는 사용자
2015. 8. 28. 08:19 프로그래밍/Python

LISTS & DICTIONARIES

Python Lists and Dictionaries 1/14

Introduction to Lists

List는 여러가지 데이터조각들을 모아놓은 데이터타입의 종류이다.

List이름 = [item1, item2] 와같은 형식으로 정의한다.

문제

The list zoo_animals has three items (check them out on line 1). 

Go ahead and add a fourth! Just enter the name of your favorite animal (as a "string") on line 1, after the final comma but before the closing ].

Python Lists and Dictionaries 2/14

Access by Index

List에 저장되어있는 값들을 사용하기 위해서는 인덱스라는것을 통하여 가능하다.( ex> list_name[index] )

인덱스는 0번부터 시작한다.(리스트의 첫번째 값이 1번이아닌 0번으로 지정된다.)

문제

Write a statement that prints the result of adding the second and fourth items of the list. Make sure to access the list by index!

Python Lists and Dictionaries 3/14

New Neighbors

리스트의 인덱스 값을 통하여 리스트에 새로운값을 저장할수있다.

zoo_animals[2] = "hyena" 라고 값을 저장하였을때 이미 2번인덱스에 값이 저장되어있더라도 2번인덱스와 그뒷번 인덱스의 값들이 

자동으로 하나씩 밀려서 저장된다.

문제

Write an assignment statement that will replace the item that currently holds the value "tiger" with another animal (as a string). It can be any animal you like.

Python Lists and Dictionaries 4/14

Late Arrivals & List Length

리스트의 길이는 가변적이다 . 만약 3개의 item이 저장되어있는 리스트( 길이 = 3 )에 새로운 item을 저장하게되면 길이가 4로 늘어난다.

list_name.append('x')를 사용하면 인덱스에 관계없이 가장 뒤쪽에 x라는 item이 하나 추가된다.

문제

01. On lines 5, 6, and 7, append three more items to the suitcase list, just like the second line of the example above. (Maybe bring a bathing suit?)

02. Then, set list_length equal to the length of the suitcase list.

Python Lists and Dictionaries 5/14

List Slicing

리스트의 인덱스를 이용하여 리스트의 특정 부분을 참조할수 있다.

slice = letters[1:3] -> letter 리스트에서 1번인덱스 부터 3번인덱스 까지 ( 1<= slice < 3) slice에 저장한다.

문제

01. On line 4, create a list called middle containing only the two middle items from suitcase.

02. On line 5, create a list called last made up only of the last two items from suitcase.

Python Lists and Dictionaries 6/14

Slicing Lists and Strings

문자열도 여러개의 문자가 리스트형태로 저장된 형태이다 , 따라서 리스트와 마찬가지로 특정부분을 참조할수 있다.

또 , list_name[:2] 는 0번인덱스부터 2번까지, list_name[2:] 는 2번부터 마지막인덱스까지 참조된다.

문제

01. Assign to dog a slice of animals from index 3 up until but not including index 6.

02. Assign to frog a slice of animals from index 6 until the end of the string.

Python Lists and Dictionaries 7/14

Maintaining Order

리스트내에서 특정한 값의 인덱스를 찾아낼수도 있다. list_name.index("x") -> list_name 리스트에서 "x"의 인덱스

또, 특정부분에 값을 삽입할수 있다. list_name.insert(3,"x") -> list_name 리스트의 3번 인덱스에 "x" 값을 삽입.

문제

01. Use the .index(item) function to find the index of "duck". Assign that result to a variable called duck_index.

02. Then .insert(index, item) the string "cobra" at that index.

Python Lists and Dictionaries 8/14

For One and All

리스트에 있는 모든 값을 참조하고 싶을때, for 루프문을 사용하면 된다.

for variable in list_name:

~~~~~

-> list_name 리스트에 있는 모든 값 ( variable 에 저장 )에 대하여 ~~~~를 수행한다.

문제

Write a statement in the indented part of the for-loop that prints a number equal to 2 * number for every list item.

Python Lists and Dictionaries 9/14

More with 'for'

sort() 를 이용하여 리스트내의 값들을 정렬할 수 있다.

list_name.sort() -> list_name 리스트의 값을 알파벳순or오름차순 으로 정렬한다.(알파벳과 숫자가 같이 있을경우 숫자먼저)

문제

01. Write a for-loop that iterates over start_list and .append()s each number squared (x ** 2) to square_list.

02. Then sort square_list!

Python Lists and Dictionaries 10/14

This Next Part is Key

dictionary 는 list와 비슷하지만, index값이 아닌 key값으로 값을 참조한다. key 값은 문자열이나 숫자 모두 가능하다.

dic = {'key1' : 1,'key2' : 2} -> dic이라는 dictionary를 선언하고 key1은 1이라는 값을 가리키고, key2는 2라는 값을 가리킨다.

문제

Print the values stored under the 'Sloth' and 'Burmese Python' keys. Accessing dictionary values by key is just like accessing list values by index:

residents['Puffin']

Python Lists and Dictionaries 11/14

New Entries

dictionary 는 list와 마찬가지로 값을 추가할수 있다.

dict_name[new_key] = new_value 

문제

Add at least three more key-value pairs to the menu variable, with the dish name (as a "string") for the key and the price (a float or integer) as the value. Here's an example:

menu['Spam'] = 2.50

Python Lists and Dictionaries 12/14

Changing Your Mind

dictionary의 값을 변경하거나 삭제할수 있다.

del  dict_name[key_name] ->key_name에 해당되는 값을 삭제한다.

dict_name[key] = new_value -> key에 해당하는 값을 new_value로 변경한다.

문제

Delete the 'Sloth' and 'Bengal Tiger' items from zoo_animals using del.


Set the value associated with 'Rockhopper Penguin' to anything other than 'Arctic Exhibit'.

Python Lists and Dictionaries 13/14

Remove a Few Things

list에서도 dictionary의 del 과같이 저장되어있는 값을 삭제할수 있다.

list_name.remove("xxx") -> list_name 리스트에서 "xxx"값을 삭제

문제

Remove 'dagger' from the list of items stored in the backpack variable.

Python Lists and Dictionaries 14/14

It's Dangerous to Go Alone! Take This

복습해보자.

문제

01. Add a key to inventory called 'pocket'

02. Set the value of 'pocket' to be a list consisting of the strings 'seashell', 'strange berry', and 'lint'

03. .sort() the items in the list stored under the 'backpack' key

04. Then .remove('dagger') from the list of items stored under the 'backpack' key

05. Add 50 to the number stored under the 'gold' key


A Day at the Supermarket 1/13

BeFOR We Begin
연습을 하기전에 for 루프문을 한번더 복습하고 가자.
for루프문은 list나 dictionary의 가장 작은 인덱스(0번) 부터 가장마지막 인덱스 까지 모두 참조한다.

문제
Use a for loop to print out all of the elements in the list names.



A Day at the Supermarket 1/13
This is KEY!
dictionary도 list와 같이 for 루프문에 사용할수 있다.
dictionary를 for루프문을 통하여 참조하게 되면 특정한 순서없이 참조된다.

문제
Use a for loop to go through the webster dictionary and print out all of the definitions.

A Day at the Supermarket 3/13

Control Flow and Looping
for루프문에서 반복되는 도중에 특정한 item에 특정한 작업?이 필요할때 조건문을 사용한다.

문제
01. Like step 2 above, loop through each item in the list called a.
02. Like step 3 above, if the number is even, print it out. You can test if the item % 2 == 0 to help you out.


A Day at the Supermarket 4/13

Lists + Functions
함수에서도 list형태의 값을 매개변수로 입력받거나 반환할수 있다.

문제
Write a function that counts how many times the string "fizz" appears in a list.

01. Write a function called fizz_count that takes a list x as input.
02. Create a variable count to hold the ongoing count. Initialize it to zero.
03. for each item in x:, if that item is equal to the string "fizz" then increment the count variable.
04. After the loop, please return the count variable.
05. For example, fizz_count(["fizz","cat","fizz"]) should return 2.


A Day at the Supermarket 5/13

String Looping


문제
Run the code to see string iteration in action!


A Day at the Supermarket 6/13

Your Own Store!
연습 ( supermarket )
dictionary변수 만들기

문제
01. Create a new dictionary called prices using {} format like the example above.
02. Put these values in your prices dictionary, in between the {}:

"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
Yeah, this place is really expensive. (Your supermarket subsidizes the zoo from the last course.)


A Day at the Supermarket 7/13

Investing in Stock
dictionary변수 만들기

문제
Create a stock dictionary with the values below.
"banana": 6
"apple": 0
"orange": 32
"pear": 15

A Day at the Supermarket 8/13

Keeping Track of the Produce
for 루프문 사용하여 dictionary 값 참조하기

문제
01. Loop through each key in prices.
02. Like the example above, for each key, print out the key along with its price and stock information. Print the answer in the following format:
apple
price: 2
stock: 0
Like the example above, because you know that the prices and stock dictionary have the same keys, you can access the stock dictionary while you are looping through prices.

When you're printing, you can use the syntax from the example above.


A Day at the Supermarket 9/13

Something of Value
for 루프문 사용하여 dictionary 값 참조하기

문제
Let's determine how much money you would make if you sold all of your food.

01. Create a variable called total and set it to zero.
02. Loop through the prices dictionaries.
03. For each key in prices, multiply the number in prices by the number in stock. Print that value into the console and then add 04. it to total.
05. Finally, outside your loop, print total.


A Day at the Supermarket 10/13

Shopping at the Market
list변수 만들기

문제
First, make a list called groceries with the values "banana","orange", and "apple".



A Day at the Supermarket 11/13

Making a Purchase
list,dictionary를 사용하는 함수 작성

문제
01. Define a function compute_bill that takes one argument food as input.
02. In the function, create a variable total with an initial value of zero.
03. For each item in the food list, add the price of that item to total.
04. Finally, return the total.
Ignore whether or not the item you're billing for is in stock.

Note that your function should work for any food list.


A Day at the Supermarket 12/13

Stocking Out
list,dictionary를 사용하는 함수 작성

문제
Make the following changes to your compute_bill function:

While you loop through each item of food, only add the price of the item to total if the item's stock count is greater than zero.
If the item is in stock and after you add the price to the total, subtract one from the item's stock count.


A Day at the Supermarket 13/13

Let's Check Out!

문제
Click Save & Submit Code to finish this course.



[ASP.NET MVC]Ninject 사용법

Posted by 알 수 없는 사용자
2015. 8. 23. 21:40 프로그래밍/.NET

이전 글에서 Dependency Injection에 대해 소개했는데 이번에는 ASP.NET MVC에 적용할 수 있는 컨테이너인 Ninject를 알아보자.

어플리케이션에서 인터페이스를 사용하고 의존성을 주입하여 각 구성요소들 간에 의존성을 분리해보도록 하자.


1. 프로젝트에 Ninject 추가하기


[그림 1]

프로젝트에 Ninject를 사용하기 위해서는 NuGet패키지 관리를 이용한다. 

프로젝트에서 마우스 우클릭 -> NuGet 패키지 관리를 선택 후 오른쪽 상단 검색창에서 ninject를 검색하면 [그림 1]과 같은 화면이 나오고 설치를 누른다.

설치 후 프로젝트의 참조를 보면 ninject가 추가된 것을 볼 수 있다.

 

[코드 1]

코드에서 Ninject를 사용하기 위해서는 먼저 Ninject 커널을 생성해야 한다. 이후에 인터페이스를 사용하려는 클래스와 바인드하는 작업을 한다.

[코드 1]의 3번째 줄은 커널을 생성한 부분이고, 5번째 줄은 IShoesFactory인터페이스를 NShoes와 바인딩시키는 부분이다.


[코드 2]

바인딩한 클래스를 전달하기 위해서는 [코드 2]의 7줄과 같이 Get메서드를 사용한다.

추가로 Ninject를 이용해 인터페이스와 클래스간에 바인딩 작업을 통해 여러 의존성 체인형성도 가능하다.


[코드 3]
만약 인터페이스와 클래스를 바인딩 할 때 속성값을 전달 하고 싶을 경우에는 [코드 3]의 5번째 줄과 같이 WithPropertyValue함수를 이용한다.
파라미터로 속성이름과 속성값을 전달 하고 속성값 전달 시 따옴표 안에 속성이름을 적어주면 된다.

위와같이 Ninject를 이용하여 의존성 주입을 하고 그에 따른 관심사의 분리가 가능하다

[Android] Permission, 권한

Posted by 알 수 없는 사용자
2015. 8. 10. 16:35 프로그래밍/Android


<uses-permission android:name="android.permission.INTERNET"/>  - 인터넷을 사용함

위치

 ACCESS_FINE_LOCATION

 위치정보 확인함

 ACCESS_MOCK_LOCATION

 위치정보 확인함

WIFI , NETWORK

 ACCESS_WIFI_STATE

 wifi 연결을 확인함

 CHANGE_WIFI_STATE

 wifi 체인지를 확인함

 ACCESS_NETWORK_STATE

 네트웍이 연결된것을 확인할수 있게함

부팅

 RECEIVE_BOOT_COMPLETED

 부팅완료를 확인할수있게함

외장메모리

 WRITE_EXTERNAL_STORAGE

 외장메모리 사용

녹음

RECODER_AUDIO 

 녹음이 가능하게 함

 ACCESS_CHECKIN_PROPERTIES

 체크인데이터베이스의_속성테이블로_액세스

 ACCESS_COARSE_LOCATION

 코스_로케이션_액세스_(Cell-ID/WiFi)

 ACCESS_FINE_LOCATION

 파인로케이션_액세스(GPS)

 ACCESS_LOCATION_EXTRA_COMMANDS

 로케이션_옵션_커맨드_액세스

 ACCESS_MOCK_LOCATION

 목_로케이션_프로바이더_생성_(테스트용)

 ACCESS_NETWORK_STATE 

 네트워크_상태_접근


ACCESS_SURFACE_FLINGER         서피스_플링거_접근                
ACCESS_WIFI_STATE              WiFi상태_접근                     
ADD_SYSTEM_SERVICE             시스템서비스_추가                 
BATTERY_STATS                  배터리_상태                       
BLUETOOTH                      블루투스                          
BLUETOOTH_ADMIN                블루투스_어드민                   
BRICK                          디바이스_실효성_지정              
BROADCAST_PACKAGE_REMOVED      제거된_패키지에_대한_notification_브로드캐스트
BROADCAST_SMS                  SMS에_대한_브로드캐스트           
BROADCAST_STICKY               인텐트_브로드캐스트               

CALL_PHONE                     통화                              
CALL_PRIVILEGED                통화(긴급전화_포함)               
CAMERA                         카메라                            
CHANGE_COMPONENT_ENABLED_STATE 컴포넌트의_실효성_변경            
CHANGE_CONFIGURATION           컨피그_변경                       
CHANGE_NETWORK_STATE           통신상태_변경                     
CHANGE_WIFI_STATE              WiFi상태_변경                     

CLEAR_APP_CACHE                어플리케이션_캐시_클리어          
CLEAR_APP_USER_DATA            어플리케이션의_유저데이터_클리어  
CONTROL_LOCATION_UPDATES       위치정보_갱신                     
DELETE_CACHE_FILES             캐시파일_제거                     
DELETE_PACKAGES                패키지_제거                       
DEVICE_POWER                   전원상태에_대한_로우레벨_접근     
DIAGNOSTIC                     진단리소스_읽고쓰기               
DISABLE_KEYGUARD               키_가드_끄기_DUMP_덤?            
EXPAND_STATUS_BAR              상태표시줄_확장                   
FACTORY_TEST                   팩토리_테스트                     
FLASHLIGHT                     플래시라이트                      
FORCE_BACK                     포스백                            
GET_ACCOUNTS                   어카운트_획득                     
GET_PACKAGE_SIZE               패키지_획득                       
GET_TASKS                      태스크_획득                       
HARDWARE_TEST                  하드웨어테스트                    
INJECT_EVENTS                  유저이벤트_키/트랙볼              
INSTALL_PACKAGES               패키지_인스톨                     
INTERNAL_SYSTEM_WINDOW         내부_시스템윈도_활용              
INTERNET                       인터넷                            
MANAGE_APP_TOKENS              어플리케이션_토큰관리             
MASTER_CLEAR                   마스터_클리어                     
MODIFY_AUDIO_SETTINGS          오디오설정_편집                   
MODIFY_PHONE_STATE             전화상태_편집                     

MOUNT_UNMOUNT_FILESYSTEMS      파일시스템_편집                   
PERSISTENT_ACTIVITY            액티비티_지속                     
PROCESS_OUTGOING_CALLS         전화_발신처리_접근                
READ_CALENDAR                  캘린더_읽어오기                   
READ_CONTACTS                  주소록_읽어오기                   
READ_FRAME_BUFFER              프레임버퍼_읽어오기               
READ_INPUT_STATE               입력상태_읽어오기                 
READ_LOGS                      로그_읽어오기                     
READ_OWNER_DATA                owner_data읽어오기                
READ_PHONE_STATE               통화상태_읽어오기_READ_SMS_SMS읽어오기
READ_SYNC_SETTINGS             동기설정_읽어오기                 
READ_SYNC_STATS                동기상태_읽어오기                 
REBOOT                         reboot                            
RECEIVE_BOOT_COMPLETED         boot완료                          
RECEIVE_MMS                    MMS수신                           
RECEIVE_SMS                    SMS수신                           
RECEIVE_WAP_PUSH               WAP수신                           
RECORD_AUDIO                   오디오_수신                       
REORDER_TASKS                  태스크_Z오더                      
RESTART_PACKAGES               패키지_리스타트                   
SEND_SMS                       SMS송신                           
SET_ACTIVITY_WATCHER           액티비티_왓쳐지정                 
SET_ALWAYS_FINISH              액티비티_전체_종료                
SET_ANIMATION_SCALE            스케일_애니메이션_지정            
SET_DEBUG_APP                  디버그어플리케이션_지정           
SET_ORIENTATION                스크린_로테이션지정               
SET_PREFERRED_APPLICATIONS     자주_사용하는_어플리케이션_지정   
SET_PROCESS_FOREGROUND         포어그라운드_처리지정             
SET_PROCESS_LIMIT              제한처리_지정                     
SET_TIME_ZONE                  타임존_지정                       
SET_WALLPAPER                  배경화면_지정                     
SET_WALLPAPER_HINTS            배경화면_힌트_지정                
SIGNAL_PERSISTENT_PROCESSES    지속처리_시그널_지정              
STATUS_BAR                     상태표시줄_지정                   
SUBSCRIBED_FEEDS_READ          서브스트립드_피즈_읽어오기        
SUBSCRIBED_FEEDS_WRITE         서브스트립드_피즈_쓰기            
SYSTEM_ALERT_WINDOW            알림_윈도우                       
VIBRATE                        진동                              
WAKE_LOCK                      알람                              
WRITE_APN_SETTINGS             APN설정_쓰기                      
WRITE_CALENDAR                 캘린더_쓰기                       
WRITE_CONTACTS                 주소록_쓰기                       
WRITE_GSERVICES                G서비스_쓰기                      
WRITE_OWNER_DATA               owner_data쓰기                    
WRITE_SETTINGS                 설정_쓰기
WRITE_SMS                      SMS쓰기 
WRITE_SYNC_SETTINGS            동기설정_쓰기


'프로그래밍 > Android' 카테고리의 다른 글

[Android] Fragment 생명주기  (621) 2015.08.10
[Android] Activity 생명주기  (11170) 2015.08.10
[Android Facebook SDK] 1.Facebook SDK import  (4) 2015.07.28