Skip to main content

Iterators, Generators, and Decorators in Python

I worked through Iterators, Generators and Decorators sections of the Computational Statistics in Python tutorial, and although this code is similar to the tutorial, it is modified in ways to make it retainable to myself:

 # Iterators can be created from sequences with the built-in function iter()  
 xs = [n for n in range(10)]  
 x_iter = iter(xs)  
 [x for x in x_iter]  
 for x in x_iter:  
 # Generators  
 # Functions containing the 'yield' keyword return iterators  
 # After yielding, the function retains its previous state  
 def limit_seats(n):  
   """Limits number and counts down"""  
   for i in range(n, 0, -1):  
     yield i  
 counter = limit_seats(10)  
 for count in counter:  
 # Iterators can also be created with 'generator expressions'  
 # which can be coded similar to list generators but with parenthesis  
 # in place of square brackets  
 maxUsers = [x for x in range(10)]  
 for x in maxUsers:  
 # Many built-in Python functions return iterators including file handlers  
 for line in open('requirements.txt'):  
 # Decorators  
 # Here is a simple decorator to time an arbitrary function  
 def func_timer(func):  
   """Times how long the function took."""  
   def f(*args, **kwargs):  
     import time  
     start = time.time()  
     results = func(*args, **kwargs)  
     print("Elapsed: %.2fs" % (time.time() - start))  
 def fibonacciWithCacheWithTimer(n, cache={0:1, 1:1}):  
     return cache[n]  
     cache[n] = fibonacci(n-1) + fibonacci (n-2)  
     return cache[n]  
 [fibonacciWithCacheWithTimer(n) for n in range(10)]  

Popular posts from this blog

Decision Tree in R, with Graphs: Predicting State Politics from Big Five Traits

This was a continuation of prior explorations, logistic regression predicting Red/Blue state dichotomy by income or by personality. This uses the same five personality dimensions, but instead builds a decision tree. Of the Big Five traits, only two were found to useful in the decision tree, conscientiousness and openness.

Links to sample data, as well as to source references, are at the end of this entry.

Example Code

# Decision Tree - Big Five and Politics library("rpart") # grow tree input.dat <- read.table("BigFiveScoresByState.csv", header = TRUE, sep = ",") fit <- rpart(Liberal ~ Openness + Conscientiousness + Neuroticism + Extraversion + Agreeableness, data = input.dat, method="poisson") # display the results printcp(fit) # visualize cross-validation results plotcp(fit) # detailed summary of splits summary(fit) # plot tree plot(fit, uniform = TRUE, main = "Classific…

Mean Median, and Mode with R, using Country-level IQ Estimates

Reusing the code posted for Correlations within with Hofstede's Cultural Values, Diversity, GINI, and IQ, the same data can be used for mean, median, and mode. Additionally, the summary function will return values in addition to mean and median, Min, Max, and quartile values:

Example Code
oecdData <- read.table("OECD - Quality of Life.csv", header = TRUE, sep = ",") v1 <- oecdData$IQ # Mean with na.rm = TRUE removed NULL avalues mean(v1, na.rm = TRUE) # Median with na.rm = TRUE removed NULL values median(v1, na.rm = TRUE) # Returns the same data as mean and median, but also includes distribution values: # Min, Quartiles, and Max summary(v1) # Mode does not exist in R, so we need to create a function getmode <- function(v) { uniqv <- unique(v) uniqv[which.max(tabulate(match(v, uniqv)))] } #returns the mode getmode(v1)
Example Results
> oecdData <- read.table("OECD - Quality of L…

Chi-Square in R on by State Politics (Red/Blue) and Income (Higher/Lower)

This is a significant result, but instead of a logistic regression looking at the income average per state and the likelihood of being a Democratic state, it uses Chi-Square. Interpreting this is pretty straightforward, in that liberal states typically have cities and people that earn more money. When using adjusted incomes, by cost of living, this difference disappears.

Example Code
# R - Chi Square rm(list = ls()) stateData <- read.table("CostByStateAndSalary.csv", header = TRUE, sep = ",") # Create vectors affluence.median <- median(stateData$Y2014, na.rm = TRUE) affluence.v <- ifelse(stateData$Y2014 > affluence.median, 1, 0) liberal.v <- stateData$Liberal # Solve pol.Data = table(liberal.v, affluence.v) result <- chisq.test(pol.Data) print(result) print(pol.Data)
Example Results
Pearson's Chi-squared test with Yates' continuity correction data: pol.Data X-squared = 12.672, df …