Friday, April 14, 2023

Ch 5 - Strings in Python

What is a string?

  • A string is a sequence characters.
  • When we write “hello world!” what computer sees is this:

h

e

l

l

o

w

o

r

l

d

!

0

1

2

3

4

5

6

7

8

9

10

11

j

a

c

k

s

m

i

t

h

0

1

2

3

4

5

6

7

8

9

String Indexing

Just a string

f

o

o

b

a

r

position

0

1

2

3

4

5

string

b

o

b

position

0

1

2

string

a

l

i

c

e

position

0

1

2

3

4

string

h

e

l

l

o

position

0

1

2

3

4

A Word About String Indexing

Indexing starts from 0 Indexing ends at len() - 1 >>> s = 'rakesh' >>> s[0] 'r' >>> s[1] 'a' >>> s[2] 'k' >>> s[3] 'e' >>> s[4] 's' >>> s[5] 'h' >>> s[6] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: string index out of range >>>

First Set of Questions on Strings

1. Declare a string variable

2. Print the third letter from that string

3. Print the length of the string variable

Q: If last index of a string is 15, what is it’s length?

Answer: 16

Q: If the length is 7, what is the last index?

What is a slice and why is it needed?

  • With indexing: we can access a character in the string.
  • What if I ask you to extract just “Jack” for me?
  • What about just “Smith”?
  • What about “Junior”?

J

a

c

k

S

m

i

t

h

J u n i o r

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

Building a slice

  • For Jack: starting index is: 0, ending index is: 3
  • So, the slice is: [0:4]
  • For Smith: starting index is: 5, ending index is: 9
  • So, the slice is: [5:10]
  • For Junior: starting index is: 11, ending index is: 16
  • So, the slice is: [11:17]
>>> x = "Jack Smith Junior"
>>> x[0:4]
'Jack'
>>> x[5:10]
'Smith'
>>> x[11:17]
'Junior'
>>>  

J

a

c

k

S

m

i

t

h

J u n i o r

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

Demonstrating Negative Step For a Slice

  • Let us say that this time we set step = -1
  • Then, the traversing of the string would happen from right to left.
  • Now, let us say start index: 15
  • Now, let us say end index: 5
  • This will traverse the string from right to left: from index 15 to index 6 because it is exclusive of end index.
>>> x[15:5:-1]
'oinuJ htim'
>>>     

J

a

c

k

S

m

i

t

h

J u n i o r

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

One more example: For Step > 1

  • Now, let us say our step = 2
  • This time it will not traverse each index, it will increment by 2 to pick an index.
  • And, start index is: 0
  • End index is: 17 (Why 17? Because slicing is exclusive of end index.)

J

a

c

k

S

m

i

t

h

J u n i o r

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

>>> x[0:17:2]
'Jc mt uir'
>>>     

What is a Slice?

  • A slice has three parts.
  • First part is: start index
  • Second part is: end index
  • Third part is: step (optional)
  • Representation: [start index: end index: step]

Default values

  • Start index: 0
  • End index: len(mylist) or len(mystr) when step is positive.
  • Step: 1
  • Negative step means direction of traversing is from right to left.

Slice (example)

j

a

c

k

s

m

i

t

h

0

1

2

3

4

5

6

7

8

9

If the string “jack smith” is given to you, then what all possible values can start index take?

Answer: 0, 1, 2, ..., 7, 8, 9

Let’s assume that step = 1.

What all possible values can end index take?

Answer: it depends on start index.

>>> x = 'jack smith'

>>> x[5:9]

'smit'

>>> x[5:2]

''

Problems on slice expansion.

  • What is the expansion of [2:7]
  • Start index is 2. End index is 7. Step takes the default value: 1 --> [2:7:1]
  • What is the expansion of [:2]
  • Start index is not given. Takes the default of 0. End index is given 2 --> [0:2:1]
  • What is the expansion of [3:]
  • One colon is there. Step is optional. So step takes the default value. Start index is given to be 3. End index takes the default value: len() --> [3:len():1]
  • What is the expansion of [:]
  • Read as: End to end. All the default values will be there --> [0:len():1]
  • What is the expansion of [::-1]
  • This comes in handy when you want to reverse a string.
  • Since start index is not there and end index is also not there, we would assume that it would go end to end. And since step is negative we would traverse the list from right to left.
  • But it is not equal to [0:len(x):-1]

String Slicing

  • String is a sequence of characters.
  • X = ‘jack smith’
  • x[0] # j
  • x[1] # a
  • x[2] # c
  • Q: What if you want to take out a substring?
  • Substring: shorter string from a longer string.
  • Syntax: x[start index : end index : step] # exclusive of end index
  • Returns the string from “start index” to “end index - 1”.
  • X[0:2] # slicing:- start index: 0, end index: 2

What is the output of following slicing based code:

  • x = "jack smith"
  • print(x[2])
  • print(len(x))
  • print(x[0:2])
  • print(x[5:8])
  • print(x[5:100])
  • # Python is intelligent about end index.
  • # If you give an end index larger than the last index, it automatically picks up the last index.

Solution:

j

a

c

k

s

m

i

t

h

0

1

2

3

4

5

6

7

8

9

Problem on index and slicing

  • Q: Print all the characters from even indices (inc. 0) of your name.
  • Q: Print all the characters from odd indices of your name.
  • Q: Print every second character of your name.
  • name1 = "Ashish Jain" # Ahs an
  • name2 = "Sonia and Johanth"
  • temp = name1[::2] # Start index, end index, step (default value of step is 1)
  • print(temp)
  • temp3 = name2[1::2]
  • print(temp3)

Solution on index and slicing

>>> x = 'vikash gupta'

>>> x[0:len(x):2]

'vks ut'

>>>

>>> x[1:len(x):2]

'iahgpa'

>>>

Follow-up Question

  • Q: What is the difference when single colon is used and when double colon is used?
  • If there is only one colon while indexing a string:
  • You have to assume that step is not mentioned and it is equal to 1 (the default value).
  • name[0::1] # end index is maximum value possible
  • name[::2] # start index: 0, end index: max value, step: 2
  • name[:] # start index: 0, end index: len(), step: 1

>>> x

'vikash gupta'

>>> x[:]

'vikash gupta'

>>> x[::]

'vikash gupta'

Second Set of Questions on Strings

  • 1. Reverse the string
  • 2. Check if a string is a palindrome.
  • Note: Palindrome is a string that is spelled the same way forward and backward. For example: mam, madam, malayalam.

Solutions

>>> x

'vikash gupta'

>>> x[::-1]

'atpug hsakiv'

>>> y = 'madam'

>>> y == y[::-1]

True

>>> z = 'malayalam'

>>> z == z[::-1]

True

>>>

>>> x == x[::-1]

False

More on Strings

Some Commonly Used String Methods

count(): Returns the number of times a specified value occurs in a string

startswith(): Returns true if the string starts with the specified value

endswith(): Returns true if the string ends with the specified value

  • Form validation of an email ID

isalpha(): Returns True if all characters in the string are in the alphabet

  • Usage: Form validation

isdigit(): Returns True if all characters in the string are digits

  • Usage: Form validation

isspace(): Returns True if all characters in the string are whitespaces

  • Usage: Form validation

islower(): Returns True if all characters in the string are lower case

isupper(): Returns True if all characters in the string are upper case

lower(): Converts a string into lower case

upper(): Converts a string into upper case

  • Used in palindrome check.

split(): Splits the string at the specified separator, and returns a list

  • Usage: File processing

splitlines(): Splits the string at line breaks and returns a list

  • Usage: File processing

strip(): Returns a trimmed version of the string

zfill(): Fills the string with a specified number of 0 values at the beginning

  • Left padding a string with 0s (ex. phn no)

Note About String in Python

  • A line about Python String from the book "Pg 191, Learning Python (O'Reilly, 5e)":
  • Strictly speaking, Python strings are categorized as immutable sequences, meaning that the characters they contain have a left-to-right positional order and that they cannot be changed in place. In fact, strings are the first representative of the larger class of objects called sequences that we will study here. Pay special attention to the sequence operations introduced in this post, because they will work the same on other sequence types we’ll explore later, such as lists and tuples.
  • Note: All string methods returns new values. They do not change the original string.

Table 7-1. Common string literals and operations

Operation Interpretation
S = '' Empty string
S = "spam's" Double quotes, same as single
S = 's\np\ta\x00m' Escape sequences
S = """...multiline...""" Triple-quoted block strings
S = r'\temp\spam' Raw strings (no escapes)
print(S) # \temp\spam
B = b'sp\xc4m' Byte strings in 2.6, 2.7, and 3.X
print(B) # b'sp\xc4m'
U = u'sp\u00c4m' Unicode strings in 2.X and 3.3+
print(U) # spÄm
S1 + S2 Concatenate
S * 3 repeat
S[i] Index
S[i:j] slice
len(S) length
"a %s parrot" % 'kind' String formatting expression
print("a %s parrot" % 'kind') # a kind parrot
"a {0} parrot".format('kind') String formatting method in 2.6, 2.7, and 3.X
S.find('pa') String methods (see ahead for all 43): search
print('a parrot'.find('pa')) # 2
S.rstrip() remove whitespace from end
print("!" + " okay ".rstrip() + "!") # ! okay!
S.strip() remove whitespace from beginning and end
print("!" + " okay ".strip() + "!") # !okay!
S.replace('pa', 'xx') replacement
print("parrot".replace('pa', 'xx')) # xxrrot
S.split(',') split on delimiter
S.isdigit() content test
S.lower()
S.upper()
case conversion
print("Parrot".lower()) # parrot
print("parrot".upper()) # PARROT
S.endswith('spam') end test
print("is this yours".endswith("yours")) # True
print("my parrot".startswith("my")) # True
'spam'.join(strlist) delimiter join
S.encode('latin-1') Unicode encoding
B.decode('utf8') Unicode decoding, etc.
for x in S: print(x) Iteration
'spam' in S membership
[c * 2 for c in S] list comprehension to create a new list
map(ord, S) map(ord, "hello") # [104, 101, 108, 108, 111]
map(lambda x: 10*x, [1,2,3,4]) # [10, 20, 30, 40]
re.match('sp(.*)am', line) Pattern matching: library module

Thursday, April 13, 2023

Vomiford-MD Ondansteron Tablet

Vomiford -MD Tablet
Prescription Required

Manufacturer/ Marketer: Leeford Healthcare Ltd

SALT COMPOSITION: Ondansetron (4mg)

Storage: Store below 30°C

Product introduction

Vomiford -MD Tablet is an antiemetic medicine commonly used to control nausea and vomiting due to certain medical conditions like stomach upset. It is also used to prevent nausea and vomiting caused due to any surgery, cancer drug therapy, or radiotherapy. Vomiford -MD Tablet may be used alone or with other medications and can be taken with or without food. Your doctor will suggest the appropriate dose depending on what you are taking it for. The first dose is normally taken before the start of surgery, chemotherapy, or radiotherapy. After these treatments, take any further doses as prescribed by your doctor (normally only for a few days at most). Take it regularly at the same time(s) each day to get the most benefit. Be careful not to take too much. This medicine does not relieve other side effects associated with cancer treatments. Also, it has little effect on vomiting caused by motion sickness. The most common side effects of taking this medicine include headache, diarrhea, or constipation and feeling tired. These symptoms should disappear when you stop taking the medicine. However, if these side effects bother you or do not go away, your doctor may be able to suggest ways of preventing or reducing them. Before taking this medicine, tell your doctor if you have heart or liver problems or a blockage in your stomach or intestines. Also, tell your doctor about any other medicines you might be taking, especially medicines to treat epilepsy, heart problems, cancer, and depression. These may affect, or be affected by, this medicine. If you are pregnant or breastfeeding, ask for advice from your doctor. Uses of Vomiford Tablet MD Treatment of Nausea Treatment of Vomiting Benefits of Vomiford Tablet MD In Treatment of Nausea Vomiford -MD Tablet blocks the action of chemicals in the body that can make you feel or be sick. It is often used to prevent nausea and vomiting that may be caused by cancer chemotherapy and radiation treatment (in adults and children aged 4 years and older). It is usually taken both before and after chemotherapy or radiation. This medicine helps you recover more comfortably from these treatments. It is also effective at preventing nausea and vomiting after an operation (in adults only). The dose will depend on what you are being treated for but always take this medicine as it is prescribed. How Vomiford Tablet MD works Vomiford -MD Tablet is an antiemetic medication. It works by blocking the action of a chemical messenger (serotonin) in the brain that may cause nausea and vomiting during anti-cancer treatment (chemotherapy) or after surgery.

Fact Box

Chemical Class: Carbazole Derivative Habit Forming: No Therapeutic Class: GASTRO INTESTINAL Action Class: Serotonin antagonists (5-HT3 antagonists)

Tuesday, April 11, 2023

Python Books (Apr 2023)

Download Books
1.
Fluent Python
Luciano Ramalho, 2015

2.
Automate the Boring Stuff with Python: Practical Programming for Total Beginners
Al Al Sweigart, 2015

3.
Head First Python
2010

4.
Python Cookbook: Recipes for Mastering Python 3
Brian K. Jones, 2011

5.
Learn Python the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Zed Shaw, 2013

6.
Python Crash Course, 2nd Edition: A Hands-On, Project-Based Introduction to Programming
Eric Matthes, 2019

7.
Learning Python
Mark Lutz, 2002

8.
Python Crash Course: A Hands-On, Project-Based Introduction to Programming
Eric Matthes, 2015

9.
Think Python: An Introduction to Software Design
Allen B. Downey, 2002

10.
Python Tricks: A Buffet of Awesome Python Features
Dan Bader, 2017

11.
Learning Python
Mark Lutz, 1999

12.
Python for Data Analysis
Wes McKinney, 2011

13.
Programming Python
Mark Lutz, 1996

14.
Python for Everybody: Exploring Data Using Python 3
Charles Severance, 2016

15.
Learning Python: Powerful Object-Oriented Programming
Mark Lutz, 2000

16.
Introduction to Machine Learning with Python: A Guide for Data Scientists
Sarah Guido, 2016

17.
Python Crash Course, 3rd Edition: A Hands-On, Project-Based Introduction to Programming
Eric Matthes, 2023

18.
Python Programming: An Introduction to Computer Science
John M. Zelle, 2003

19.
Machine Learning in Python: Essential Techniques for Predictive Analysis
2015

20.
Learn Python in One Day and Learn it Well: Python for Beginners with Hands-on Project
Jamie Chan, 2015

21.
Elements of Programming Interviews in Python: The Insiders' Guide
Tsung-Hsien Lee, 2018


22.
Python Data Science Handbook
Jacob T. Vanderplas, 2016

23.
Deep Learning with Python
François Chollet, 2017


24.
Effective Python: 90 Specific Ways to Write Better Python
Brett Slatkin, 2019

25.
Hands-On Machine Learning with Scikit-Learn and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems
Geron Aurelien, 2017

26.
Python Pocket Reference, 4/E (Covers Python 3 X & 2.6)
Mark Lutz, 2014

27.
Invent Your Own Computer Games with Python, 4th Edition
Al Al Sweigart, 2016

28.
Effective Python: 59 Specific Ways to Write Better Python
Brett Slatkin, 2015

29.
Python for Kids: A Playful Introduction To Programming
Jason R. Briggs, 2012

30.
Grokking Algorithms: An Illustrated Guide for Programmers and Other Curious People
Aditya Bhargava, 2015

31.
Python Programming for the Absolute Beginner
Dawson, 2003

32.
Python 3 Object Oriented Programming
Dusty Phillips, 2010


33.
The Python Bible 7 in 1: Volumes One To Seven (Beginner, Intermediate, Data Science, Machine Learning, Finance, Neural Networks, Computer Vision)
Florian Dedov, 2020

34.
Impractical Python: Projects Playful Programming Activities to Make You Smarter
Lee Vaughan, 2018

35.
Python in a nutshell
Alex Martelli, 2003

36.
Python Cookbook
Alex Martelli, 2002

37.
Coding for Kids: Python: Learn to Code with 50 Awesome Games and Activities
Adrienne B. Tacke, 2019

38.
Natural Language Processing with Python
Steven Bird, 2009

39.
Beyond the Basic Stuff with Python: Best Practices for Writing Clean Code
Al Al Sweigart, 2020


40.
Practical Statistics for Data Scientists: 50+ Essential Concepts Using R and Python
Andrew Bruce, 2017

41.
Black Hat Python, 2nd Edition: Python Programming for Hackers and Pentesters
Justin Seitz, 2021


42.
Django for Beginners: Build websites with Python and Django
William Vincent, 2018

43.
The Big Book of Small Python Projects: 81 Easy Practice Programs
Al Al Sweigart, 2021

44.
Serious Python: Black-Belt Advice on Deployment, Scalability, Testing, and More
Julien Danjou, 2018

45.
Data Structure and Algorithmic Thinking with Python
Narasimha Karumanchi, 2015

46.
Python All-in-One For Dummies
Alan Simpson, 2019


47.
Let Us Python
Yashavant Kanetkar, 2019

48.
Python Programming For Beginners: Learn The Basics Of Python Programming (Python Crash Course, Programming for Dummies)
James Tudor, 2019

49.
Python Distilled
David M. Beazley, 2021

50.
Python for Beginners: A Crash Course Guide to Learn Python in 1 Week
Timothy C. Needham, 2017

51.
Cracking Codes with Python: An Introduction to Building and Breaking Ciphers
Al Al Sweigart, 2018

52.
Python for Everybody : Exploring Data in Python 3
Charles Russell Severance, Sue Blumenberg
CreateSpace Independent (2016)
Tags: Technology,List of Books,Python,

Sunday, April 9, 2023

Lesson 2 - Some more examples of Sets (and a Venn Diagram for each)

set1 - set2 Intersection set2 - set1
Set1 Size:
Diff Size:
Intersection Size: Set2 Size:
Diff Size:


Introduction to Sets (Also an exercise in Data Visualization)

What are sets?

Definition 1 (from NCERT) A set is a well-defined collection of objects. The following points may be noted : (i) Objects, elements and members of a set are synonymous terms. (ii) Sets are usually denoted by capital letters A, B, C, X, Y, Z, etc. (iii) The elements of a set are represented by small letters a, b, c, x, y, z, etc. Some examples of sets: (i) Odd natural numbers less than 10, i.e., 1, 3, 5, 7, 9 (ii) The rivers of India (iii) The vowels in the English alphabet, namely, a, e, i, o, u (iv) Various kinds of triangles (v) Prime factors of 210, namely, 2,3,5 and 7 (vi) The solution of the equation: x2 – 5x + 6 = 0, viz, 2 and 3. We give below a few more examples of sets used particularly in mathematics, viz. N : the set of all natural numbers Z : the set of all integers Q : the set of all rational numbers R : the set of real numbers Z+ : the set of positive integers Q + : the set of positive rational numbers, and R + : the set of positive real numbers. Definition 2 Sets: grouping of elements and each element in the group is unique.

Two basic types of sets: Overlapping sets and Non-overlapping sets.

Overlapping Sets

If there is one or more element present in both sets, the sets are called to be overlapping.

Example of Overlapping Sets

Set1: First six natural numbers.
Set2: First three natural numbers and first three alphabets.
Now two sets together in a Venn Diagram.
set1 - set2 Intersection set2 - set1
Set1 Size:
Diff Size:
Intersection Size: Set2 Size:
Diff Size:

Example of Non-Overlapping Sets

Non-overlapping sets are better known as Disjoint Sets.

Set1: First six natural numbers.
Set2: First six alphabets.
Now two sets together in a Venn Diagram.
set1 - set2 Intersection set2 - set1
Set1 Size:
Diff Size:
Intersection Size: Set2 Size:
Diff Size:

Nomenclature for sets that are 'Overlapping'

Subset and Superset Relation

If each element of set A is in set B, and also we have some extra elements present in set B which are not in set A: Then, we call set A a subset and set B a superset. A superset has more number of elements than a subset. Set1: Letters from the word 'Rhythm'.
Set2: English Consonants.
Now two sets together in a Venn Diagram.
set1 - set2 Intersection set2 - set1
Set1 Size:
Diff Size:
Intersection Size: Set2 Size:
Diff Size:

Equal Sets

If superset and subset have same number of elements, such that the two sets are fully overlapping each other then we call them 'Equal Sets'.
Tags: Mathematical Foundations for Data Science,JavaScript,Technology,

Thursday, April 6, 2023

Twitter takes its algorithm ‘open-source,’ as Elon Musk promised (Apr 2023)

Twitter has released the code that chooses which tweets show up on your timeline to GitHub and has put out a blog post explaining the decision. It breaks down what the algorithm looks at when determining which tweets to feature in the For You timeline and how it ranks and filters them.

According to Twitter’s blog post, “the recommendation pipeline is made up of three main stages.” First, it gathers “the best Tweets from different recommendation sources,” then it ranks those tweets with “a machine learning model.” Lastly, it filters out tweets from people you’ve blocked, tweets you’ve already seen, or tweets that are not safe for work, before putting them on your timeline.

The post also further explains each step of the process. For example, it notes that the first step looks at around 1,500 tweets and that the goal is to make the For You timeline around 50 percent tweets from people that you follow (who are called “In-Network”) and 50 percent tweets from “out-of-network” accounts that you don’t follow. It also says that the ranking is meant to “optimize for positive engagement (e.g., Likes, Retweets, and Replies)” and that the final step will try to make sure that you’re not seeing too many tweets from the same person.


Of course, the most detail will be available by picking through the code, which researchers are already doing.

CEO Elon Musk has been promising the move for a while — on March 24th, 2022, before he owned the site, he polled his followers about whether Twitter’s algorithm should be open source, and around 83 percent of the responses said “yes.” In February, he promised it would happen within a week before pushing back the deadline to March 31st earlier this month.

Musk tweeted that Friday’s release was “most of the recommendation algorithm” and said that the rest would be released in the future. He also said that the hope is “that independent third parties should be able to determine, with reasonable accuracy, what will probably be shown to users.” In a Space discussing the algorithm’s release, he said the plan was to make it “the least gameable system on the internet” and to make it as robust as Linux, perhaps the most famous and successful open-source project. “The overall goal is to maximize on unregretted user minutes,” he added.

Musk has been preparing his audience to be disappointed in the algorithm when they see it (which is, of course, making a big assumption that people will actually understand the complex code). He’s said it’s “overly complex & not fully understood internally” and that people will “discover many silly things” but has promised to fix issues as they’re discovered. “Providing code transparency will be incredibly embarrassing at first, but it should lead to rapid improvement in recommendation quality,” he tweeted.

There is a difference between code transparency, where users will be able to see the mechanisms that choose tweets for their timelines, and code being open source, where the community can actually submit its own code for consideration and use the algorithm in other projects. While Musk has said it’ll be open source, Twitter will have to actually do the work if it wants to earn that label. That involves figuring out systems for governance that decide what pull requests to approve, what user-raised issues deserve attention, and how to stop bad actors from trying to sabotage the code for their own purposes.

Twitter says people can submit pull requests that may eventually end up in its codebase.

The company does say it’s working on this. The readme for the GitHub says, “We invite the community to submit GitHub issues and pull requests for suggestions on improving the recommendation algorithm.” It does, however, go on to say that Twitter’s still in the process of building “tools to manage these suggestions and sync changes to our internal repository.” But Musk’s Twitter has promised to do many things (like polling users before making major decisions) that it hasn’t stuck with, so the proof will be in whether it actually accepts any community code.

The decision to increase transparency around its recommendations isn’t happening in a bubble. Musk has been openly critical of how Twitter’s previous management handled moderation and recommendation and orchestrated a barrage of stories that he claimed would expose the platform’s “free speech suppression.” (Mostly, it just served to show how normal content moderation works.)

But now that he’s in charge, he’s faced a lot of backlash as well — from users annoyed about their For You pages shoving his tweets in their faces to his conservative boosters growing increasingly concerned about how little engagement they’re getting. He’s argued that negative and hate content is being “max deboosted” in the site’s new recommendation algorithms, a claim outside analysts without access to the code have disputed.

Twitter is also potentially facing some competition from the open-source community. Mastodon, a decentralized social network, has been gaining traction in some circles, and Twitter co-founder Jack Dorsey is backing another similar project called Bluesky, which is built on top of an open-source protocol.
Tags: Technology,Management,Investment,FOSS

Tuesday, April 4, 2023

Brief Intro to Functions in JavaScript (Lesson 3)

Learning JavaScript as a Second Language

Functions in JavaScript

Four Parts of a Function

Function objects are created with function literals: // Create a variable called add and store a function in it that adds two numbers. var add = function (a, b) { return a + b; }; A function literal has four parts. The first part is the reserved word function. The optional second part is the function’s name. The function can use its name to call itself recursively. The name can also be used by debuggers and development tools to identify the function. If a function is not given a name, as shown in the previous example, it is said to be anonymous. The third part is the set of parameters of the function, wrapped in parentheses. Within the parentheses is a set of zero or more parameter names, separated by commas. These names will be defined as variables in the function. Unlike ordinary variables, instead of being initialized to undefined, they will be initialized to the arguments supplied when the function is invoked. The fourth part is a set of statements wrapped in curly braces. These statements are the body of the function. They are executed when the function is invoked.

Invocation

Invoking a function suspends the execution of the current function, passing control and parameters to the new function. In addition to the declared parameters, every function receives two additional parameters: this and arguments. The this parameter is very important in object oriented programming, and its value is determined by the invocation pattern. There are four patterns of invocation in JavaScript: 1. the method invocation pattern, 2. the function invocation pattern, 3. the constructor invocation pattern, and 4. the apply invocation pattern. The patterns differ in how the bonus parameter “this” is initialized. The invocation operator is a pair of parentheses that follow any expression that produces a function value. The parentheses can contain zero or more expressions, separated by commas. Each expression produces one argument value. Each of the argument values will be assigned to the function’s parameter names. There is no runtime error when the number of arguments and the number of parameters do not match. If there are too many argument values, the extra argument values will be ignored. If there are too few argument values, the undefined value will be substituted for the missing values. There is no type checking on the argument values: any type of value can be passed to any parameter.

Out of these four patterns, "Method Invocation Pattern" and "Constructor Invocation Pattern" are important in understanding and working with KnockoutJS.

The Method Invocation Pattern

When a function is stored as a property of an object, we call it a method. When a method is invoked, “this” variable is bound to that object. If an invocation expression contains a refinement (that is, a . dot expression or [subscript] expression), it is invoked as a method: // Create myObject. It has a value and an increment method. The increment method takes an optional parameter. If the argument is not a number, then 1 is used as the default. var myObject = { value: 0, increment: function (inc) { this.value += typeof inc === 'number' ? inc : 1; } }; myObject.increment( ); document.writeln(myObject.value); // 1 myObject.increment(2); document.writeln(myObject.value); // 3 A method can use this to access the object so that it can retrieve values from the object or modify the object. The binding of this to the object happens at invocation time. This very late binding makes functions that use this highly reusable. Methods that get their object context from this are called public methods.

The Constructor Invocation Pattern

JavaScript is a prototypal inheritance language. That means that objects can inherit properties directly from other objects. The language is class-free. This is a radical departure from the current fashion. Most languages today are classical. Prototypal inheritance is powerfully expressive, but is not widely understood. JavaScript itself is not confident in its prototypal nature, so it offers an object-making syntax that is reminiscent of the classical languages. Few classical programmers found prototypal inheritance to be acceptable, and classically inspired syntax obscures the language’s true prototypal nature. It is the worst of both worlds. If a function is invoked with the new prefix, then a new object will be created with a hidden link to the value of the function’s prototype member, and this will be bound to that new object. The new prefix also changes the behavior of the return statement. Functions that are intended to be used with the new prefix are called constructors. By convention, they are kept in variables with a capitalized name. If a constructor is called without the new prefix, very bad things can happen without a compile-time or runtime warning, so the capitalization convention is really important. Use of this style of constructor functions is not recommended. // Create a constructor function called Quo. It makes an object with a status property. var Quo = function (string) { this.status = string; }; // Give all instances of Quo (called a Class in classical programming like C++) a public method called get_status. Quo.prototype.get_status = function ( ) { return this.status; }; // Make an instance of Quo. var myQuo = new Quo("confused");

Return Statement

When a function is invoked, it begins execution with the first statement, and ends when it hits the } that closes the function body. That causes the function to return control to the part of the program that invoked the function. The return statement can be used to cause the function to return early. When return is executed, the function returns immediately without executing the remaining statements. A function always returns a value. If the return value is not specified, then undefined is returned. If the function was invoked with the new prefix and the return value is not an object, then this (the new object) is returned instead.

Exception Handling

JavaScript provides an exception handling mechanism. Exceptions are unusual (but not completely unexpected) mishaps that interfere with the normal flow of a program. When such a mishap is detected, your program should throw an exception: The throw statement interrupts execution of the function. It should be given an exception object containing a name property that identifies the type of the exception, and a descriptive message property. You can also add other properties. The exception object will be delivered to the catch clause of a try statement: If an exception is thrown within a try block, control will go to its catch clause. A try statement has a single catch block that will catch all exceptions. If your handling depends on the type of the exception, then the exception handler will have to inspect the name to determine the type of the exception.

Recursion

A recursive function is a function that calls itself, either directly or indirectly. Recursion is a powerful programming technique in which a problem is divided into a set of similar subproblems, each solved with a trivial solution. Generally, a recursive function calls itself to solve its subproblems. Example: Factorial Problem (n!)
Tags: Technology,JavaScript,