Updated code with average redshift