this program is to find the second largest number this works for most of the inputs but it is not working for the following inputs.
n=4
a1 = '-7 -7 -7 -7 -6'
a1=[int(arr_temp) for arr_temp in a1.strip().split(' ')]
print(a1)
largest = max(a1)
largest2 = 0
for i in range(0,len(a1)):
if ((a1[i]>largest2 or a1[i]<0) and largest2<largest and a1[i]!=largest):
largest2 = a1[i]
print(largest2)
Setting largest2 to 0 just complicates the if statement later. Set it to the smallest value in the array and it becomes clearer.
n=4
a1 = '-7 -7 -7 -7 -6'
a1=[int(arr_temp) for arr_temp in a1.strip().split(' ')]
print(a1)
largest = max(a1)
largest2 = min(a1)
for i in range(0,len(a1)):
if (a1[i] > largest2) and (a1[i] < largest):
largest2 = a1[i]
print(largest2)
Note that if the array is large, the call to min becomes non-trivial. In that case you could set largest2 to the smallest value possible (on that note, this link might be useful)
Related
Definition of H Index used in this algorithm
Supposing a relational expression is represented as y = F(x1, x2, . . . , xn), where F returns an integer number greater than 0, and the function is to find a maximum value y satisfying the condition that there exist at least y elements whose values are not less than y. Hence, the H-index of any node i is defined as
H(i) = F(kj1 ,kj2 ,...,k jki)
where kj1, kj2, . . . , kjki represent the set of degrees of neighboring nodes of node i.
Now I want to find the H Index of the nodes of the following graphs using the algorithm given below :
Graph :
Code (Written in Python and NetworkX) :
def hindex(g, n):
nd = {}
h = 0
# print(len(list(g.neighbors(n))))
for v in g.neighbors(n):
#nd[v] = len(list(g.neighbors(v)))
nd[v] = g.degree(v)
snd = sorted(nd.values(), reverse=True)
for i in range(0,len(snd)):
h = i
if snd[i] < i:
break
#print("H index of " + str(n)+ " : " + str(h))
return h
Problem :
This algorithm is returning the wrong values of nodes 1, 5, 8 and 9
Actual Values :
Node 1 - 6 : H Index = 2
Node 7 - 9 : H Index = 1
But for Node 1 and 5 I am getting 1, and for Node 8 and 9 I am getting 0.
Any leads on where I am going wrong will be highly appreciated!
Try this:
def hindex(g, n):
sorted_neighbor_degrees = sorted((g.degree(v) for v in g.neighbors(n)), reverse=True)
h = 0
for i in range(1, len(sorted_neighbor_degrees)+1):
if sorted_neighbor_degrees[i-1] < i:
break
h = i
return h
There's no need for a nested loop; just make a decreasing list, and calculate the h-index like normal.
The reason for 'i - 1' is just that our arrays are 0-indexed, while h-index is based on rankings (i.e. the k largest values) which are 1-indexed.
From the definition of h-index: For a non-increasing function f, h(f) is max i >= 0 such that f(i) >= i. This is, equivalently, the min i >= 1 such that f(i) < i, minus 1. Here, f(i) is equal to sorted_neighbor_degrees[i - 1]. There are of course many other ways (with different time and space requirements) to calculate h.
Everyone,
the task is as follows: to write a program that prints the max and min number of a Python console input.
For example, we enter (the "5" above is "n" => the count of the numbers to be entered):
5
10
30
504
0
60
The Output should say:
Max number: 504
Min number: 0
Below is the solution - could someone please explain to me the definition of max_number = -sys.maxsize and min_number = sys.maxsize (why are both variables' values actually the opposite to their actual ones) along with the if conditional statement, how should the iterations go so that the output is correct?
import sys
n = int(input())
max_number = -sys.maxsize
min_number = sys.maxsize
for i in range(n):
current_number = int(input())
if current_number > max_number:
max_number = current_number
if current_number < min_number:
min_number = current_number
print(f'Max number: {max_number}')
print(f'Min number: {min_number}')
Thanks!
You can do something like this
n = int(input())
numbers = []
for i in range(n):
numbers.append(int(input()))
print(f'Max number: {max(numbers)}')
print(f'Min number: {min(numbers)}')
Here is quick and easy solution
user_input = input("Enter the numbers separated by a space ").split()
int_list = list(map(int, user_input))
print ("Max number:",max(int_list), "\nMin number:",min(int_list))
# Output
Enter the numbers separated by a space 5 10 30 504 0 60
Max number: 504
Min number: 0
You can complete the task with just 3 lines of code and here user no need to provide number of integers or count
Explanation to your Question:
import sys
max_number = -sys.maxsize
min_number = sys.maxsize
print(max_number, max_number)
# Output
-9223372036854775807 9223372036854775807
As you can see sys.maxmsize (9223372036854775807) is the greatest integer and sys.maxmsize(-9223372036854775807) is the smallest integer.
For first If condition you are considering smallest integer for comparison so that even smallest value will be stored as max value for first iteration and it gets updated as it find out greater value than that.
In your example, 5 would be consider as max_number in first iteration of for loop
why?
first iteration of for loop
if 5 > -9223372036854775807 # max_number = -9223372036854775807, current_number = 5 hence condition is true i.e. 5 > -9223372036854775807
max_number = 5 # max_number updated with 5
# max_number is 5 now
second iteration of for loop
if 10 > max_number # max_number = 5, current_number = 10 hence 10 > 5 condition is true
max_number = 10 # max_number updated with 10
# max_number is 10 now
and so on...at the end 504 will remain max_number
For second If condition situation is exactly opposite
first iteration of for loop
if 5 < 9223372036854775807 # min_number = 9223372036854775807, current_number = 5 hence condition is true i.e. 5 < 9223372036854775807
min_number = 5 # min_number has become 5 now
# min_number is 5 now
.
. # min_number we remain 5 for 2nd, 3rd and 4th iterations because 10, 30 and 504 are greater than 5 hence failed to satisfy if condition
.
fifth iteration of for loop
if 0 < min_number # min_number = 5, current_number=0
min_number = 0 # min_number has become 0 now
# min_number is 0 now
At the end 0 will remain min_number
sys.maxmsize is the greatest integer a variable can take.
Thus, the program first initialise the max_number to the smaller number possible. By doing, it is sure that it will not miss a number in the list.
Then, it goes inside the inputs and each time it sees a number greater than the actual max_number it updates the max_number.
That being said, the first update will **always** occurs for the first item in the loop (because all the number are greater than the smallest number).
It makes the opposite for the `min_number` (takes the greatest number and then go down).
Does this help you?
For more precision on sys.maxsize look at the docs:
https://docs.python.org/3/library/sys.html
(search for maxsize)
https://docs.python.org/3/library/sys.html
"sys.maxsize
An integer giving the maximum value a variable of type Py_ssize_t can take. It’s usually 2**31 - 1 on a 32-bit platform and 2**63 - 1 on a 64-bit platform."
So you are initialising the largest and smallest possible integers so the comparison will be able to compare if numbers entered are smaller or larger than the possible maximum or minimum.
>>> -sys.maxsize
-9223372036854775807
>>> sys.maxsize
9223372036854775807
>>>
You want them to be the opposite for the initial loop, else you have nothing to compare against. So anything should be larger than the theoretical minimum and vice versa.
For max_number, each iteration in the for loop will check if the newly entered number is larger then the max_number value. If so, this new value will become the max_number value. After all iterations are processed, the variable max_numbers holds the value of the largest number. To make sure the value entered in the first iteration always wins compared to the max_number current value, you initialize max_number with the lowest possible value (-sys.maxsize). This way any entered number will always be larger and thus will become the new value of max_number.
begin: max_number = -sys.max_number
IN=10 -> max_number = 10
IN=30 -> max_number = 30
IN=504 -> max_number = 504
IN=0 -> max_number = 504
IN=60 -> max_number = 504
The same logic is used for min_number but in the other direction: initialise it with the highest possible value so the value of the first iteration will always be smaller and win the comparison.
I am trying to calculate the Demarker Indicator in Python. Following describes how to calculate it:
Choose a predetermined period “X” (Standard value is “14”, although a value of “8” or “9” tends to be more sensitive);
Calculate DeMax = High – Previous High if >0, otherwise DeMax = 0;
Calculate DeMin = Previous Low – Low if >0, otherwise DeMin = 0;
DeM = MA of DeMax/(MA of DeMax + MA of DeMin).
Following is my attempt, df is a dataframe contains open high low close price with date as index:
df['DeMax'] = df['High'] - df['High'].shift(1)
df['DeMin'] = df['Low'].shift(1)-df['Low']
# Method 1: df['DeMax'][df['DeMax'] < 0] = 0.0
# Method 2: df[df['DeMax']< 0]['DeMax'] = 0.0
If I use Method 1, it is ok. But if I use Method2, I will get warning SettingWithCopyWarning, even I use copy method like this df['DeMax'] = df['High'].copy() - df['High'].copy().shift(1) won't solve the issue.
I have also checked that df['DeMax'][df['DeMax'] < 0] and df[test['DeMax']< 0]['DeMax'] are same pandas series, so why they behave differently if I try to assign values?
Also, if I do something like this
df['DeMax'] = df['High'] - df['High'].shift(1)
df['DeMin'] = df['Low'].shift(1)-df['Low']
a = df['DeMax'][df['DeMax'] < 0]
a = 0
Then a will be 0 instead of a pandas series, but I also expect df['DeMax'][df['DeMax'] < 0] will be 0, which does not happen, could anyone help? Thanks.
You are looking for .loc
df.loc[df['DeMax'] < 0,'DeMax']=0 # it will change all value less that 0 to 0
I am trying to achieve a column-style for converting celcius to fahrenheit.
My question: When I run it, the numbers are lining up nicely. However the c and f are aligned left and are not above the numbers. Why is this?
Here is my code:
def convert(celc):
fahr = celc * 1.8 + 32
return fahr
def table():
format_str = '{0:10} {1:10}'
c = 'c'
f = 'f'
cfhead = format_str.format(c, f)
print(cfhead)
for graden in range(-40,30,10):
result = format_str.format(convert(graden), graden)
print(result)
table()
Use > in your format to always align to the right:
format_str = '{0:>10} {1:>10}'
The default is for strings to be left-aligned, numbers to be right-aligned.
From the Format Specification Mini-Language documentation:
'<'
Forces the field to be left-aligned within the available space (this is the default for most objects).
'>'
Forces the field to be right-aligned within the available space (this is the default for numbers).
With an explicit alignment formatter you get your desired output:
>>> table()
c f
-40.0 -40
-22.0 -30
-4.0 -20
14.0 -10
32.0 0
50.0 10
68.0 20
I want to search for a specific word in a text file and return its position. This code reads the text fine...
fid = fopen('jojo-1 .txt','r');
while 1
tline = fgetl(fid);
if ~ischar(tline)
break
end
end
but when I add this code
U = strfind(tline, 'Term');
it returns [] although the string 'Term' exists in the file.
Can you please help me?
For me, it works fine:
strfind(' ertret Term ewrwerewr', 'Term')
ans =
9
Are you sure that 'Term' is really in your line?
I believe that your ~ischar(tline) makes the trouble because the code "breaks" when the tline is not char..so the strfind cannot find anything.
so the mayor change I made is to actually search for the String at the line which was identified as a line with some characters.
I tried a little bit modification of your code on my TEXT file:
yyyy/mmdd(or -ddd)/hh.h):2011/-201/10.0UT geog Lat/Long/Alt= 50.0/ 210.0/2000.0
NeQuick is used for topside Ne profile
URSI maps are used for the F2 peak density (NmF2)
CCIR maps are used for the F2 peak height (hmF2)
IRI-95 option is used for D-region
ABT-2009 option is used for the bottomside thickness parameter B0
The foF2 STORM model is turned on
Scotto-97 no L option is used for the F1 occurrence probability
TBT-2011 option is used for the electron temperature
RBY10+TTS03 option is used for ion composition
Peak Densities/cm-3: NmF2= 281323.9 NmF1= 0.0 NmE= 2403.3
Peak Heights/km: hmF2= 312.47 hmF1= 0.00 hmE= 110.00
Solar Zenith Angle/degree 109.6
Dip (Magnetic Inclination)/degree 65.76
Modip (Modified Dip)/degree 55.06
Solar Sunspot Number (12-months running mean) Rz12 57.5
Ionospheric-Effective Solar Index IG12 63.3
TEC [1.E16 m-2] is obtained by numerical integration in 1km steps
from 50 to 2000.0 km. t is the percentage of TEC above the F peak.
-
H ELECTRON DENSITY TEMPERATURES ION PERCENTAGES/% 1E16m-2
km Ne/cm-3 Ne/NmF2 Tn/K Ti/K Te/K O+ N+ H+ He+ O2+ NO+ Clust TEC t/%
0.0 -1 -1.000 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 7.7 75
5.0 -1 -1.000 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 7.7 75
10.0 -1 -1.000 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 7.7 75
it is an output from one Ionospheric model but that is not important:)
so I used following Matlab code to find where it string TEMPERATURES
out = fopen('fort.7'); % Open function
counter = 0; % line counter (sloppy but works)
while 1 % infinite loop
tline = fgetl(out); % read a line
counter = counter + 1; % we are one line further
if ischar(tline) % if the line is string
U = strfind(tline, 'TEMPERATURES'); % where the string start (if at all)
if isfinite(U) == 1; % if it is a number actually
break % we found it, lets go home
end
end
end
results:
counter = 26
U = 27