w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Finding the average of n numbers with Python
You only need one loop to work. Just ask you question, get the input, and loop. When you enter no, then the loop will exit and compute your average. print("This program 'is' designed to find the average of n numbers you input ") #print statement that introduces the average finder counter = 0 #this counter will count how many numbers the user has inserted into the program and will be used as denominator sum_of_numbers = 0 #this number is set as 0 as currently the sum is 0, as more numbers are inputed, they will be added together first_question = input('''Would you like to enter a number? Type "yes" if you do, and "no" if you don't. ''') #takes input of yes or no to see whether user wants to find average of numbers while first_question == "yes" : ent_num = int(input("Enter y

Categories : Python

Average of 2d list by only adding single row and finding the average of that single row
>>> L = [['x','y',1], ['x','y',1], ['x','y',2]] >>> sum(entry[-1] for entry in L) / float(len(L)) 1.3333333333333333 This is same as: >>> sum(entry[2] for entry in L) / float(len(L)) since the last position is index 2.

Categories : Python

what is the average time, that an average process, running on an average kernel, using an average scheduler, gets in one active cycle?
Linux uses 100 milliseconds as the scheduler quantum, if that's what you were asking, in your own, convoluted way :-) There's nothing saying a process has to use their entire quantum and, in fact, if they release early, I think their priority gets bumped up a bit as a reward.

Categories : C

Finding an average SQL
I'm going to guess a little bit on what's going on from your comment, so I think your JOIN is off a bit. Try this: Select Company.company_id, company.Company_Name, avg(UserJobRating.Total_Rating) from company inner join jobs on jobs.Company_id = company.company_id inner join UserJobRating on jobs.Job_id = UserJobRating.Job_ID group by company.company_id SQL Fiddle Demo Without seeing your table definitions, this is a bit of a guess, but I would bet you're producing a Cartesian Product with the UserJobRating table with this statement: on Job_id = UserJobRating.Job_ID

Categories : Mysql

SQL finding average between dates
Declare @dt_to datetime Declare @dt_from datetime set @dt_to = convert(datetime,'2013-7-8') set @dt_from = convert(datetime,'2013-7-15') Update tableName Set avg_paid_volume = (cns_amt / datediff(d,@dt_to,@dt_from)) datediff is key here

Categories : SQL

Finding Average using nested queries on another table
Here's an example that you can execute in LINQPad EDIT: updated to show handling of nulls for sub query void Main() { var restaurants = new List<Restaurant>(); restaurants.Add(new Restaurant(1, "McDonalds")); restaurants.Add(new Restaurant(2, "Wendy's")); restaurants.Add(new Restaurant(3, "KFC")); var comments = new List<Comment>(); comments.Add(new Comment(1, 1, "I love clowns!", 9.5)); comments.Add(new Comment(2, 1, "Disgusting", 1.0)); comments.Add(new Comment(3, 1, "Average", 5.0)); comments.Add(new Comment(4, 2, "Hmmm tasty", 8.5)); comments.Add(new Comment(5, 2, "Yuck", 4.0)); // Edit - removed comment for KFC, updated code below to handle nulls var restaurantsWithRatings = restaurants.Select(r => new { Re

Categories : C#

having issues with finding the average run time of a block
Your method is mostly ok so far, except you don't need to branch out i == 1 from i > 1 – { 1.times { yield } is functionally equivalent to just calling yield. yield doesn't return anything on its own. It is a keyword that indicates the block given to the method should be called, and can optionally be fed variables that would in turn get passed to the block, e.g: class String def each_character_in_reverse_order each_char.to_a.reverse_each do |char| yield char end end end "hello".each_character_in_reverse_order do |c| puts c.upcase end #=> # O # L # L # E # H In the case of the tests you've linked to, the return values of the blocks are complete inconsequential, as they are only interested in how long it takes to run the block. But as you can see in the exa

Categories : Ruby

Python: Finding the average stock value for each month
Inside the if loop the sum_float and count are not made a 0, so as a program proceeds the average goes for multiple months. So try doing that and it should solve your problem. Also one more point with your logic is that are you that whether your list of tuples is sorted one if not it can lead to complications with regards to your logic.

Categories : Python

Finding the row with the highest average in a numpy array
You don't need to worry about the 0s, they shouldn't effect how the averages compare since there will presumably be one in each row. Hence, you can do something like this to get the index of the row with the highest average: >>> import numpy as np >>> complete_matrix = np.array([ ... [0, 1, 2, 4], ... [1, 0, 3, 5], ... [2, 3, 0, 6], ... [4, 5, 6, 0]]) >>> np.argmax(np.mean(complete_matrix, axis=1)) 3 Reference: numpy.mean numpy.argmax

Categories : Python

Finding average file size in MB in given directory
You could use the Average extension method: // using System.Linq; string filePath = @"DesiredFilePath"; double averageFileSize = Directory .EnumerateFiles(filePath) .Average(x => new FileInfo(x).Length);

Categories : C#

Finding average of last 3 not null values from sqlite database
I'm going to assume you have a column to_order which contains the order you want to retrieve the rows in and col which contains your numbers: select avg(col) from tbl where col is not null order by to_order desc limit 3; If you have further questions, leave a comment.

Categories : Android

UIImage and Finding the Average UIColor of Center Pixels
You are only iterating the pixels from startPoint to one less of endPoint. Maybe using for(int row = yStartPoint; row <= yEndPoint; row++) // ... for(int column = xStartPoint; column <= xEndPoint; column++) will fix it? Also you will have to adjust your rowPtr to start at your xStartPoint: const UInt8 *rowPtr = rawPixelData + bytesPerRow * row + stride * xStartPoint; Else you will be starting at x = 0 every row. And your average should be calculated like so: int numberOfPixels = (yEndPoint - yStartPoint) * (xEndPoint - xStartPoint); red /= numberOfPixels; green /= numberOfPixels; blue /= numberOfPixels; return [UIColor colorWithRed:red / 255.0 green:green / 255.0 blue:blue / 255.0 alpha:1.0f];

Categories : IOS

Finding Average of value based on count of rows in LINQ
You could just use average: var average = (from a in db.Reviews where a.ReviewsRestaurantID.Equals(id) select a.ReviewsRating).Average(); You could also do it with aggregate like this (if what you really want to do is more complicated, here is an example implementation of average): var result = db.Reviews.Where(r => r.ReviewsRestaurantID = id) .Aggregate(new () { total = 0, count = 0, avg = 0.0 }, (o, n) => { var result = new () { total = o.total+n.ReviewsRating, count = o.count+1, avg = 0.0}; result.avg = result.total / result.count; return result; }, (r) => r.avg);

Categories : C#

To stop finding running average once the condition fails?
sub = [767220, 769287, 770167, 770276, 770791, 770835, 771926, 1196500, 1199789, 1201485, 1206331, 1206467, 1210929, 1213184, 1213204, 1213221, 1361867, 1361921, 1361949, 1364886, 1367224, 1368005, 1368456, 1368982, 1369000, 1370365, 1370434, 1370551, 1371492, 1471407, 1709408, 1710264, 1710308, 1710322, 1710350, 1710365, 1710375] def runningMean(seq, n=0, total=0): #function called recursively if not seq: return [] total = total + int(seq[-1]) if int(seq[-1]) < total/float(n+1) * 0.9: # Check your condition to see if it's time to stop averaging. return [] return runningMean(seq[:-1], n=n+1, total=total) + [total/float(n+1)] avg = runningMean(sub, n = 0, total = 0) print avg print sub[-len(avg):]

Categories : Python

Finding the average length of a column as per a particular case in MySQL
I prefer the length() inside the case: SELECT u.id, AVG(LENGTH(m.body)) AS avg_msg_length, AVG(CASE WHEN m.is_retired = 'Y' THEN LENGTH(m.body) END) AS avg_msg_length_retired FROM Users u LEFT OUTER JOIN Messages m ON u.id = m.sender_id GROUP BY u.id; The 'Y' should be whatever character or string indicates truth. The problem with your query is that you are mixing character expressions (is_retired) with numeric expressions (true). Be consistent with the types. For instance, this evaluates to false: select 'true' = true; But this evaluates to true: select 1 = true;

Categories : Mysql

Finding the average of double values from the command line?
You probably meant: for (int i = 0; i < args.length; i++) As this is the main logical issue here, there are other (syntactic) problems that needs to be addressed, that others have mentioned (see @seanmk's answer, for instance, on the importance of scoping loops). (Note: this was written before @seanmk's answer was updated with additional information, when it only regarded the issue of brackets and scoping of loops).

Categories : Java

Calculating average of a set of numbers without postback
$(document).ready(function(){ $("#yourtextbox").keyup(function(){ var text = $(this).val(); var arr = text.split(','); var sum = 0; var count = 0; $.each(arr,function(index,value){ var currentItem = parseInt(value); if (!isNaN(currentItem)){ sum+= currentItem; count++; } }); console.log(sum/count); $("#result").text(sum/count); }); }); Demo

Categories : Javascript

JScript Code Won't average numbers
Update: JS Fiddle link for working, extremely simplified code using a single function and no outside variables: http://jsfiddle.net/cookies/kZZeY/ As you change the numbers in any of the boxes, the average is updated while you type. Note: I am not answering this for the purpose of doing homework, as I suspect this question might be, but because it is worthwhile to show some form handling methods in this answer because such techniques are of great general usefulness in many applications. Some of these techniques are: using this in the way it begs to be used in form event handlers iterating through form elements instead of using error-prone multiple variables (like var numberTwo = document.numbers.numTwo.value; var numberThree = document.numbers.numThree

Categories : Javascript

Find average on string field contains numbers in ralis
I solve problem with a = ActiveRecord::Base.connection.select_all("select AVG(CAST(value as integer) ) from user_stats where property = 'BEST_SCORE'") a[0]['avg'].to_i But stil think that UserStat.find_by_sql(" select AVG(CAST(value as integer) ) from user_stats where property = 'BEST_SCORE'") must raise error or return value..

Categories : SQL

How to calculate average of a column of numbers linked to each frequency bin making up a histogram, Excel 2010?
The question calls for a "wandering trace" of a scatterplot: the values of column A (plot them on the horizontal axis) are placed into bins, which therefore comprise vertical strips in the scatterplot. The values of column C (plotted on the vertical axis) are averaged within each strip. This technique smooths out and summarizes apparent trends in the scatterplot. In this example with 100 records the original data are in black and computed values are in green. Here is the wandering trace of means: The open circles plot column C (associated values) against column A (data) while the solid squares, connected with a dashed red trace, plot the bin means (column G) against the midpoints (column F). Any statistical package will provide functions for grouping data and performing operation

Categories : Excel

Finding N closest numbers
collect all the values to create a single ordered sequence, with each element tagged with the array it came from: 0(0), 2(1), 3(2), 4(0), 6(1), ... 12(3), 13(2) then create a window across them, starting with the first (0(0)) and ending it at the first position that makes the window span all the arrays (0(0) -> 7(3)) then roll this window by incrementing the start of the window by one, and increment the end of the window until you again have a window that covers all elements. then roll it again: (2(1), 3(2), 4(0), ... 7(3)), and so forth. at each step keep track of the the difference between the largest and the smallest. Eventually you find the one with the smallest window. I have the feeling that in the worst case this is O(n^2) but that's just a guess.

Categories : Python

Quickly finding if there are 2 or more equal numbers
It really depends on what other constraints you have, e.g.: Do you need to maintain the order in which the number come in? Are the numbers are only ever added, or are they deleted too? What is a more common operation: add/delete or check for dupes? What do you need to keep - the set (i.e., unique numbers) or the multiset (numbers with their multiplicities)? There are two basic options: a Binary Search Tree and a Hash Table. The former will give you O(log(n)) operations on average, the latter - O(1); the actual results will depend on what kind of stream you have (are the numbers random? increasing? follow a weird non-obvious pattern?) If you decide to go for BST, remember that you will have to keep it balanced. Example (untested) (defparameter *my-data-array* (make-array 100000)) ;;

Categories : Arrays

Finding ranges in runs of numbers
Whether you use a function from "plyr" or from base R, you need to first establish some groups. One way to detect the change in groups since your years are sequential is to look for where diff is not equal to 1. diff creates a vector of length one less than the input vector, so we'll initialize that with "1" and take the cumsum of the result. Putting that mouthful of an explanation into practice, you can try something like this: dat$id2 <- cumsum(c(1, diff(dat$year) != 1)) From here, you can use aggregate or your favorite grouping function to get the output you're looking for. aggregate(year ~ name + id2, dat, function(x) paste(min(x), max(x), sep = "-")) # name id2 year # 1 A 1 2000-2010 # 2 B 2 2000-2005 # 3 B 3 2007-2011 To use range with aggregate, you n

Categories : R

Finding Fibonacci numbers using regex
(?x) .? | ( \2?+ (\1|^.) )* .. There are a lot of things going on here which may confuse. I will go through each of these things in order to explain why the algorithm works. The match is being done on a string with the length of the regex, not the actual number. The only real data in the string is its length. \The double backslashes are just because in Java string literals backslashes have to be backslashed so that it is clear you aren't escaping something else. I won't show them in any future code in this answer. (?x): This enables extended regex mode. In this mode whitespace that is not backslashed or within a character class is ignored, allowing the regular expression to be broken into more readable parts with embedded comments. [sarand.com]. .?: This will match 0 or 1 characte

Categories : Java

Finding random numbers and a pattern from them
My results have been that the loop stops at odd places and never with abs()s different. I suspect the while() expression is wrong System.out.println("abs x "+Math.abs(targetx)); System.out.println("abs y "+Math.abs(targetx)); Check out the variable names in those lines. Part II: Each of your if statements changes the value of targetx and targety such that the values match the next if statement. As a result, every if statement executes and the values of targetx and targety at the end of the loop are the values set in the last if statement. You should be using an if-else if structure. Even if the values being set in each of the if statements did not match the next if statement, you would still want to use an if-else if structure because then java wouldn't have to check all 4 if co

Categories : Java

Finding number of k-prime numbers;
The algorithm you are using is know as Sieve of Eratosthenes. It is a well known algorithm for finding prime numbers. Now to answer your questions : 1a) What is the complexity of this code The complexity of your code is O(n log(log n)). For and input of a and b the complexity of your code is O(b log log b). The runtime is due to the fact that you first mark b/2 number then b/3 then b/5 and so on. So your runtime is b * (1/2 + 1/3 + 1/5 + 1/7 + 1/11 + ... + 1/prime_closest_to_b). What we have there is a prime harmonic series which grows asymptotically as ln(ln(b+1)) (see here). Asymptotically the upper bound is: O(b * (1/2 + 1/3 + 1/5 + 1/7 +..)) = O(b) * O(log(log(b+1))) = O(b*log(log(b)) 1b) Can it be done in O(n) This is tricky. I would say that for all practical purposes an O(n

Categories : C

Reading a text file of student names and text scores and finding an average
Oops: int i =Integer.parseInt ("TS"); This doesn't make sense. What number is "TS" supposed to represent? Edit: you state: I know that TS is not a valid number that's why I was trying to cast it to a number You can't "cast" letters to a number, again it makes no sense. You need to read in the Strings in the file and then parse those Strings, not some letters you make up. What your code should do is: read in each line in the file in a for loop inside this loop, split the String using String's split(" ") method. Use Integer.parse(...) to parse the 3rd item in the array returned. So would I use Integer.parse(String [] TS)? No, this won't even compile since you're trying to pass a String array into a method that takes a String parameter.

Categories : Java

Finding the min first value of a list of pairs of numbers in JavaScript
As Sirko said, you can do that with a simple for loop, comparing each first value with its previous value. You can also do that with the reduce1 array method, to achieve shorter code: var tuples = [[1,2], [2,4], [3,5], [5,2]]; var tupleWithMinFirstValue = tuples.reduce(function(previous, current){ return current[0] < previous[0] ? current : previous; }, [Infinity]); console.log(tupleWithMinFirstValue); http://jsfiddle.net/wAGMX/ 1 The link also provides compatibility info, and a polyfill.

Categories : Javascript

Finding numbers of annotation in same coordinate in map view
Your annotations are on a map. You need to define some bounding box around the coordinate you're interested in. From this coordinate bounding box you can calculate an MKMapRect and from that you can get the annotations inside using annotationsInMapRect:. Alternately, you own the annotations so you can search whatever data structure you have the raw annotation data saved in.

Categories : IOS

MASM code for finding prime numbers not working
Managed to fix it. Because of my poor placement of debug breakpoints I didn't realize that the edx register is being used properly. However, two other problems were present in my code. Working code is below. Notice the new jmp command right before the prime: tag, and the new reset of testNum before the return. isPrime PROC; checks if a number is prime by dividing out values less than it until it finds one that has a remainder of 0 ;or the test value reaches the number retest: inc testNum mov eax, testPrime cmp eax, testNum je prime mov edx, 0 mov eax, testPrime mov ebx, testNum div ebx mov eax, edx cmp eax, ZERO jg retest mov eax, 1 mov testNum, eax inc testPrime jmp retest prime: mov eax, 1 mov testNum, eax ret isPrime ENDP

Categories : Assembly

Can you explain this method of finding prime numbers in javascript
It's called the Sieve of Erathestenes and it's an efficient way of finding all prime numbers between zero and some upper limit integer. j = i << 1 This is a bit shift operation. It shifts an integer 1 bit to the left. Because binary is base two, this is equivalent to multiplying by two. In decimal, the equivalent operation would be shifting, say, 1 to the left and bringing in a zero to the right. It's base ten, so you end up with 10 (ten times one.) I don't believe the implementation you show is optimal. The limit to the i value can be lower -- something like sqrt(max). You can easily find some really nice animations online of this algorithm that show you what's going on in quite an intuitive way.

Categories : Javascript

SQL query to compare individual average with a group average
You don't need the first ; since it is a statement terminator. Change this : SELECT Person, Avg(Score) AS PersonAverage FROM TblScores GROUP BY Person HAVING (((Avg(Score))>(SELECT Avg(Score) AS AverageOfAllScores FROM TblScores;))); with this : SELECT Person, Avg(Score) AS PersonAverage FROM TblScores GROUP BY Person HAVING (((Avg(Score))>(SELECT Avg(Score) AS AverageOfAllScores FROM TblScores)));

Categories : Mysql

average 3rd column when 1st and 2nd column have same numbers
Like this? A = [1 4 12;1 4 14;1 4 10; 1 5 5;1 5 7]; [x,y] = consolidator(A(:,1:2),A(:,3),@mean); B = [x,y] B = 1 4 12 1 5 6 Consolidator is on the File Exchange.

Categories : Matlab

Is n operations of O(1) average time each considered O(n) in average?
Given that you are traversing all your array the second time, yes that is O(n) * O(1) (and not O(n)+O(1) as previously stated from me) (for hash lookup in average time), so you are talking about an algorithm of O(n) complexity .

Categories : Database

Finding number of permutations of 'p' numbers that sum to a given number 'n'
Contrary to my comment, this problem is actually easier to solve if we count the number of sets and the permutations of those sets at the same time. If we only need to count instead of actually generating each of the sets, we can do so directly with some simple combinatorics. Let's fix p = 3, n = 5 for our example and imagine that we have n = 5 balls: o o o o o Now the question is equivalent to, how many ways can we split the balls into groups of 3 where each group can have [0, 5] balls? Imagine if we had p - 1 = 2 sticks that we could individually place anywhere: before all five balls, after all five balls, and between any two balls. For example: | o o | o o o => (0, 2, 3) o | | o o o o => (1, 0, 4) o o o o | | o => (4, 0, 1) Notice how the questions are equivalent? Anyway

Categories : Algorithm

SQLite select average from one table and update average field from another table using trigger
To compute the average value of a specific field dynamically, use this query: SELECT AVG(value) FROM table_1 WHERE field = 'field_a'; If you want instead a view that looks like your table_2, you can define it like this: CREATE VIEW view_2 AS SELECT field, AVG(value) AS average_value FROM table_1 GROUP BY field; If you really want table_2 to be an actual table, you could compute the average values like this: UPDATE table_2 SET average_value = (SELECT AVG(value) FROM table_1 WHERE table_1.field = table_2.field); If you want table_2 to be an actual table, and want to update only those values that have changed, use a trigger like this: CREATE TRIGGER update_average_value_after_insert AFTER INSERT ON table_1 FOR EACH ROW BEGIN UPDATE

Categories : SQL

Why is Average Visit Duration different to Average Time on Page, when only one page is viewed?
Visit duration is affected by pageviews and events. Time on page is only affected by pageviews, and you need a second pageview in order to calculate the time on page for the first page. To put it another way...your events are skewing the avg visit duration metric. Technically that visit is a bounce too.

Categories : Google Analytics

Given 4 numbers of array of 1 to 10 elements. Find 3 numbers whose sum can generate all the four numbers?
Since the solution contains only 3 numbers which are in 1..10 range, brute force is an effective algorithm here (at most 1000 possibilities to check even in naive implementation). So C# code could be public static int[] BruteForce(int[] data) { HashSet<int> hs = new HashSet<int>(); for (int x = 1; x <= 10; ++x) for (int y = x; y <= 10; ++y) for (int z = y; z <= 10; ++z) { hs.Clear(); for (int i = 0; i < data.Length; ++i) hs.Add(data[i]); hs.Remove(x); hs.Remove(y); hs.Remove(z); hs.Remove(x + y); hs.Remove(x + z); hs.Remove(y + z); hs.Remove(x + y + z); if (hs.Count <= 0) return new int[] { x, y, z }; // <- Solution } return new in

Categories : Arrays

Java arraylist. I need to pass random numbers to an array list and pass them to another class to check those numbers against another set of numbers
You can always transform the random int to a string by using Integer.toString() before inserting into your array list. You can convert the String back to int using Integer.parseInt() E.g. for (int i = 0 ; i < 3 ; i++) { locations.add(Integer.toString((int)(Math.random() * 5)); }

Categories : Java

Extract string that is delimited with constant and ends with two numbers (numbers have to be included)
You can use this regex (?<=XYZs+)[a-zA-Zs,]+d+s+d+ ---------- ---------- --------- | | |->matches two numbers separated by space | |->matches names separated by , |->lookbehind assertion which checks for a XYZ followed by space before matching the string

Categories : Python



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.