Next Python in C

Introduction

Surprisingly, it seems that there are people who have become B4 and can only use C as the programming language. Well, it's true that classes only deal with C language publicly, and it's only natural. However, it would be very inefficient to use C language every time to implement a little calculation or algorithm. Declare a variable ~, allocate memory ~, oh, I forgot the semicolon. It's troublesome.

I think Python is a good way to create a prototype program. To be honest, I don't know much about others, but I think Python is fine for the time being.

I'm not a master of Python at all, but for the time being, the knowledge I've done in C is enough to write a program properly.

So, I can't think of anything to write in the Advent Calendar, so I decided to write an introductory Python article for those who have gone through the C language. The target is mainly B3 or less, rather than B3 or less. By the way, I've been using only Python2 series so far, but I thought that if I deal with Python3 series here, it would be my study, so I decided to use Python3 series.

Environment

Ah, opening a terminal with ubuntu 16.04 LTS while saying that it is troublesome to build an environment,

When I do it

Python 3.5.2 (default, Nov 17 2016, 11:45:14)


[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.

It will be. Since it will be in the input acceptance state, let's stop it with Ctrl-D for the time being. (This is called an interactive shell and will not be mentioned in this article.)

Actually Python3 is already in ubuntu. You did it. (By the way, if you do python instead of python3, Python2 will work.)

I'm not ubuntu, but I don't think I'm worried because other Linux users are strong people. Or rather, don't read this article. It's embarrassing. For Windows people, you can download the software from the official Python, and I think it would be nice to use Bash on Ubuntu on Windows or VMware to virtually install ubuntu. It could be used for other purposes. Mac person? I have a Mac, so check it out for yourself on the Mac in front of you. (I don't know if it will come in from the beginning with ubuntu.)

Hello Work

Let's get the first famous program running right away. Create the following file by naming it as print.py with vim or emacs.

print.py


print("Fuck eeic")

On the command line

$ python3 print.py


When I do

It will be. It's really easy. There is no such thing as compiling. semicolon? You should guess with a line break. I won't mention saving or executing files anymore, so let's go on and on in the same way.

variable

You don't need to declare variables in Python. Please just put what you want to substitute. You can even cast from a string to an integer. If you make a mistake, an error will occur when you execute programming, so you can do it for the time being and your spirit will be nurtured.

calc.py


a = "3"
b = 2
c = int(a) / b
print(a, b, c)

3 2 1.5

Unlike C language, and unlike Python2, it seems that integers / integers come out as decimal numbers in Python3. I'm often mistaken, so I'm grateful. If you change the operator a little and set c = int (a) // b, it will be an integer value as usual.

Control statement

ʻIf, forandwhile. while is relatively the same, but ʻif is a little, and for is different from Oita C language.

Anyway, "indent" is the most unique. In C language, the range is indicated by parentheses, but in Python, the range of control is indicated by : and indentation.

control.py


a = True
if a != True and a == False:
    print(1)
elif a == None:
    print(2)
else:
    print(3)

print(range(10))

sum = 0
for i in range(10):
    sum += i
print(sum)

sum = 0
i = 0
while True:
    sum += i
    i += 1
    if i >= 10:
        break
print(sum)
3
range(0, 10)
45
45

There are ʻif, ʻelse and another ʻelif. It's an abbreviation for else if, but it's a little weird. To the conditionandAnd of courseorBecause of that, C's&&When||It is a substitute for. I didn't notice until I got a comment, but in Python&&When||`Does not exist. Caution.

for works because I don't understandfor i in range (10):. When I print range (10), I get a better idea of range (0, 10), but for the time being, ʻi` has 0 to 9 (10-1). It is designed to loop with the integer of. Yeah I don't know.

Supplement. As you mentioned in the comment, if you use print (list (range (10))), it will be [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], and then You can see that it is a "list" to handle. In Python2, you can get this list with print (range (10)) without casting to the list, and the for introduced here is the same operation as for using the list (which will be dealt with next). It is very easy to understand that, but unfortunately the specification has changed in Python3. This is not a bad thing, it's a memory management upgrade. In this article, I'm assuming that I have enough mind to move, so I'm just trying to explain it properly as above. If you want to know more, please go to "range xrange" or "Python 2/3 difference".

The increment is sum + = 1, but note that it cannot besum ++.

I think the while remains the same. break is also the same as C language. Although not written in the code, continue is also available in C language.

Lists and dictionaries

Instead of arrays in C, Python has lists, and instead of structures, there are dictionaries. No, instead of structs is classes. But for the time being, I will introduce the dictionary because the dictionary is enough for writing the program properly.

list_dict.py


lst = [1, 2, 3]
print(lst[1])

lst.append(4)
print(lst)

lst.remove(2)
print(lst)

for neko in lst:
    print(neko)


dct = {'year':2016, 'month':12, 'day':6}
print(dct['year'])

dct['hour'] = 0
print(dct)

del dct['month']
print(dct)
2
[1, 2, 3, 4]
[1, 3, 4]
1
3
4
2016
{'year': 2016, 'day': 6, 'hour': 0, 'month': 12}
{'year': 2016, 'day': 6, 'hour': 0}

Python does not need malloc to work with lists (arrays). Python manages it for you. I'm smart.

There are some first-time notational functional things like .append () and .remove () for list variables, but they are so-called object-oriented and can only be used for objects called lists. .. It's like ʻappend (lst, 2)`. Well, don't worry, swallow it, it's just out of order. The contents of the list are called elements, but append adds the element to the end of the list, and remove removes the specified element (strictly speaking, the element closest to the beginning of the list and the same as the specified value is deleted). It is an operation.

I'm using a list to do the operation for neko in lst:, which may be a little unfamiliar. This is an operation that assigns elements to neko one by one from the list named lst and turns the loop. If lst = [1, 3, 4], then 1 for neko in the first week, 3 for neko in the second week, and neko in the third week. 4 is assigned to and goes around the loop.

I think that it is easy to understand the initial value input and the addition and deletion of elements in the dictionary. After looking at the .remove () in the list, it feels like del, but hmm, I wonder what this is. Well, what should I want to erase? del is a fairly versatile one that is also used when you want to erase other variables.

Lists and dictionaries can be anything as an element, that is, not only numbers and strings, but also lists in lists, dictionaries in dictionaries, dictionaries in lists, and so on. If you can use it well, you can manipulate most of the data with this.

function

Create your own favorite function. Speaking of the masterpiece of the function, it is swap.

swap.py


def swap(a, b):
    tmp = a
    a = b
    b = tmp
    return a, b

a = "neko"
b = "inu"

print(a, b)
a, b = swap(a, b)
print(a, b)
neko inu
inu neko

Again, you specify the range with : and indentation.

In C language, swap is realized by passing a pointer and manipulating the pointer reference destination, but in various loose Pythons, the return value of the function can be flexibly manipulated, so even such appropriate code works properly. I will. In fact, swap is just that I couldn't think of a function example, so I don't have to bother to create a function. It is made up of ʻa, b = b, a`.

However, if you write too much, you may get hurt.

list_reverse.py


def list_reverse(lst):
    lst.reverse()
    return 0

def add(a):
    a += 1
    return 0

lst = [1, 2, 3, 4, 5]
lst2 = lst
print(lst)
list_reverse(lst)
print("lst :", lst)
print("lst2:", lst2)

a=1
add(a)
print(a)
[1, 2, 3, 4, 5]
lst : [5, 4, 3, 2, 1]
lst2: [5, 4, 3, 2, 1]
1

I created a useless function list_reverse () to perform the operation .reverse () to change the order of the list in the function. It's really useless if you just pass the value.

However, I think that the original list is not affected just by passing the list to the function and reversing the order in the function, but the original list is also affected and the order is reversed. This is because the list is basically treated like a pointer. Since we pass by reference to the function, the operation of the function affects the original list.

There is an assignment with lst2 = lst, but this is also not a copy of the value. Since the list is basically passed by reference, these two lists are synchronized and are the same. The lst2, which should not be related to the evidence, is also in reverse order.

On the other hand, the variable ʻa has no effect if it is incremented by the function ʻadd (). This is because it is passed by value (like).

When I look it up, it seems that all of them are passed by reference. When the value is changed, it seems that it is divided into (1) [type that changes the reference destination] and (2) [type that suddenly secures another area and changes the reference destination]. I thought it was annoying, but it's certainly correct in terms of memory management. Reference: Passing by Python and passing by reference

import Python seems to have a lot of libraries. I'm not familiar with it, but when I look for such a function, I think that there is a library and it is well taken care of.

It was #include <> in C, but ʻimport` in Python.

import.py


import copy

def list_reverse(lst):
    lst.reverse()
    return 0

lst = [1, 2, 3, 4, 5]
lst2 = copy.deepcopy(lst)
print(lst)
list_reverse(lst)
print("lst :", lst)
print("lst2:", lst2)
[1, 2, 3, 4, 5]
lst : [5, 4, 3, 2, 1]
lst2: [1, 2, 3, 4, 5]

ʻImport copy and lst2 = copy.deepcopy (lst) . I used .deepcopy ()fromcopy's house. As you can see from the output, this time lst2 is not synchronized with lstbecause it just copied the value oflst using .deepcopy () `chan. You did it.

in conclusion

I think I've touched on the basics of Hello Work, variables, control statements, lists and dictionaries, functions, and imports. There are many parts that I haven't touched on, such as complex numbers for variables and switches for control statements ~~ (Python didn't have switches !!). Even so, if you are a person who has done all the C language, you can google if you think "Is this function not available?" There is anyway.

As I mentioned at the beginning, I wrote it with the hope that people who have only touched C language for the time being, especially those who are B3 or lower, will have a chance to touch Python. If you do each lesson assignment in C language, you won't have a body, right? It doesn't have to be Python, so you should touch other quick writing languages. I thought it would be good if I could study Python3, but in the basic part, there was only a difference about print, so it didn't make much sense after all.

Nowadays, I still can't write object-oriented programming. I will write a procedural type and surpass the situation. Even so, I have (probably) done something that seems to be research, so I think the one I wrote this time will be a little useful for doing something that seems to be research.

Even so, I wrote an uninteresting article. Oh, and I hope it will lower the hurdles for Advent Calendar.

(Thank you for the correction comment)

Recommended Posts

Next Python in C
C API in Python 3
Extend python in C ++ (Boost.NumPy)
Binary search in Python / C ++
ABC166 in Python A ~ C problem
Solve ABC036 A ~ C in Python
How to wrap C in Python
Solve ABC037 A ~ C in Python
Write C unit tests in Python
Quadtree in Python --2
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Unittest in python
Epoch in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
python C ++ notes
Plink in Python
Constant in python
python, openFrameworks (c ++)
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
flatten in python
Solve ABC175 A, B, C in Python
Algorithm in Python (ABC 146 C Binary Search
Implement FIR filters in Python and C
Write O_SYNC file in C and Python
Generate C language from S-expressions in Python
Run Python in C ++ on Visual Studio 2017
Sorted list in Python
Daily AtCoder # 36 in Python