RE: Can you help me with this memoization simple example?

2024-03-31 Thread AVI GROSS via Python-list
I am not sure if it was made clear that there is a general rule in python for 
what is HASHABLE and lists are changeable while tuples are not so the latter 
can be hashed as a simple copy of a list, albeit the contents must also be 
immutable.

The memorize function uses a dictionary to store things and thus the things are 
hashed to decide how to store it in the inner representation of a dictionary 
and anything new that you want to look up in the dictionary has similar 
considerations as it is hashed to see where in the dictionary to look for it.

Of course, if you add enough overhead and the memorize function you make gets 
relatively few requests that are identical, it may not be worthwhile.

-Original Message-
From: Python-list  On 
Behalf Of MRAB via Python-list
Sent: Sunday, March 31, 2024 3:24 PM
To: python-list@python.org
Subject: Re: Can you help me with this memoization simple example?

On 2024-03-31 09:04, marc nicole wrote:
> Thanks for the first comment which I incorporated
>
> but when you say "You can't use a list as a key, but you can use a 
> tuple as a key,
> provided that the elements of the tuple are also immutable."
>
> does it mean  the result of sum of the array is not convenient to use 
> as key as I do?
> Which tuple I should use to refer to the underlying list value as you 
> suggest?
>
I was suggesting using `tuple` on the argument:

def memoize(f):
  cache = {}

  def g(*args):
  key = tuple(args[0]), args[1]

  if key not in cache:
  cache[key] = f(args[0], args[1])

  return cache[key]

  return g

> Anything else is good in my code ?
>
> Thanks
>
> Le dim. 31 mars 2024 à 01:44, MRAB via Python-list 
>  a écrit :
>
> On 2024-03-31 00:09, marc nicole via Python-list wrote:
> > I am creating a memoization example with a function that adds up
> / averages
> > the elements of an array and compares it with the cached ones to
> retrieve
> > them in case they are already stored.
> >
> > In addition, I want to store only if the result of the function
> differs
> > considerably (passes a threshold e.g. 50 below).
> >
> > I created an example using a decorator to do so, the results
> using the
> > decorator is slightly faster than without the memoization which
> is OK, but
> > is the logic of the decorator correct ? anybody can tell me ?
> >
> > My code is attached below:
> >
> >
> >
> > import time
> >
> >
> > def memoize(f):
> >  cache = {}
> >
> >  def g(*args):
> >  if args[1] == "avg":
> >  sum_key_arr = sum(list(args[0])) / len(list(args[0]))
>
> 'list' will iterate over args[0] to make a list, and 'sum' will
> iterate
> over that list.
>
> It would be simpler to just let 'sum' iterate over args[0].
>
> >  elif args[1] == "sum":
> >  sum_key_arr = sum(list(args[0]))
> >  if sum_key_arr not in cache:
> >  for (
> >  key,
> >  value,
> >  ) in (
> >  cache.items()
> >  ):  # key in dict cannot be an array so I use the
> sum of the
> > array as the key
>
> You can't use a list as a key, but you can use a tuple as a key,
> provided that the elements of the tuple are also immutable.
>
> >  if (
> >  abs(sum_key_arr - key) <= 50
> >  ):  # threshold is great here so that all
> values are
> > approximated!
> >  # print('approximated')
> >  return cache[key]
> >  else:
> >  # print('not approximated')
> >  cache[sum_key_arr] = f(args[0], args[1])
> >  return cache[sum_key_arr]
> >
> >  return g
> >
> >
> > @memoize
> > def aggregate(dict_list_arr, operation):
> >  if operation == "avg":
> >  return sum(list(dict_list_arr)) / len(list(dict_list_arr))
> >  if operation == "sum":
> >  return sum(list(dict_list_arr))
> >  return None
> >
> >
> > t = time.time()
> > for i in range(200, 15000):
> >  res = aggregate(list(range(i)), "avg")
> >
> > elapsed = time.time() - t
> > print(res)
> > print(elapsed)
>
>
> -- 
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can you help me with this memoization simple example?

2024-03-31 Thread MRAB via Python-list

On 2024-03-31 09:04, marc nicole wrote:

Thanks for the first comment which I incorporated

but when you say "You can't use a list as a key, but you can use a 
tuple as a key,

provided that the elements of the tuple are also immutable."

does it mean  the result of sum of the array is not convenient to use 
as key as I do?
Which tuple I should use to refer to the underlying list value as you 
suggest?



I was suggesting using `tuple` on the argument:

def memoize(f):
 cache = {}

 def g(*args):
 key = tuple(args[0]), args[1]

 if key not in cache:
 cache[key] = f(args[0], args[1])

 return cache[key]

 return g


Anything else is good in my code ?

Thanks

Le dim. 31 mars 2024 à 01:44, MRAB via Python-list 
 a écrit :


On 2024-03-31 00:09, marc nicole via Python-list wrote:
> I am creating a memoization example with a function that adds up
/ averages
> the elements of an array and compares it with the cached ones to
retrieve
> them in case they are already stored.
>
> In addition, I want to store only if the result of the function
differs
> considerably (passes a threshold e.g. 50 below).
>
> I created an example using a decorator to do so, the results
using the
> decorator is slightly faster than without the memoization which
is OK, but
> is the logic of the decorator correct ? anybody can tell me ?
>
> My code is attached below:
>
>
>
> import time
>
>
> def memoize(f):
>      cache = {}
>
>      def g(*args):
>          if args[1] == "avg":
>              sum_key_arr = sum(list(args[0])) / len(list(args[0]))

'list' will iterate over args[0] to make a list, and 'sum' will
iterate
over that list.

It would be simpler to just let 'sum' iterate over args[0].

>          elif args[1] == "sum":
>              sum_key_arr = sum(list(args[0]))
>          if sum_key_arr not in cache:
>              for (
>                  key,
>                  value,
>              ) in (
>                  cache.items()
>              ):  # key in dict cannot be an array so I use the
sum of the
> array as the key

You can't use a list as a key, but you can use a tuple as a key,
provided that the elements of the tuple are also immutable.

>                  if (
>                      abs(sum_key_arr - key) <= 50
>                  ):  # threshold is great here so that all
values are
> approximated!
>                      # print('approximated')
>                      return cache[key]
>              else:
>                  # print('not approximated')
>                  cache[sum_key_arr] = f(args[0], args[1])
>          return cache[sum_key_arr]
>
>      return g
>
>
> @memoize
> def aggregate(dict_list_arr, operation):
>      if operation == "avg":
>          return sum(list(dict_list_arr)) / len(list(dict_list_arr))
>      if operation == "sum":
>          return sum(list(dict_list_arr))
>      return None
>
>
> t = time.time()
> for i in range(200, 15000):
>      res = aggregate(list(range(i)), "avg")
>
> elapsed = time.time() - t
> print(res)
> print(elapsed)


-- 
https://mail.python.org/mailman/listinfo/python-list



--
https://mail.python.org/mailman/listinfo/python-list


Re: Can you help me with this memoization simple example?

2024-03-31 Thread marc nicole via Python-list
Thanks for the first comment which I incorporated

but when you say "You can't use a list as a key, but you can use a tuple as
a key,
provided that the elements of the tuple are also immutable."

does it mean  the result of sum of the array is not convenient to use as
key as I do?
Which tuple I should use to refer to the underlying list value as you
suggest?

Anything else is good in my code ?

Thanks

Le dim. 31 mars 2024 à 01:44, MRAB via Python-list 
a écrit :

> On 2024-03-31 00:09, marc nicole via Python-list wrote:
> > I am creating a memoization example with a function that adds up /
> averages
> > the elements of an array and compares it with the cached ones to retrieve
> > them in case they are already stored.
> >
> > In addition, I want to store only if the result of the function differs
> > considerably (passes a threshold e.g. 50 below).
> >
> > I created an example using a decorator to do so, the results using the
> > decorator is slightly faster than without the memoization which is OK,
> but
> > is the logic of the decorator correct ? anybody can tell me ?
> >
> > My code is attached below:
> >
> >
> >
> > import time
> >
> >
> > def memoize(f):
> >  cache = {}
> >
> >  def g(*args):
> >  if args[1] == "avg":
> >  sum_key_arr = sum(list(args[0])) / len(list(args[0]))
>
> 'list' will iterate over args[0] to make a list, and 'sum' will iterate
> over that list.
>
> It would be simpler to just let 'sum' iterate over args[0].
>
> >  elif args[1] == "sum":
> >  sum_key_arr = sum(list(args[0]))
> >  if sum_key_arr not in cache:
> >  for (
> >  key,
> >  value,
> >  ) in (
> >  cache.items()
> >  ):  # key in dict cannot be an array so I use the sum of the
> > array as the key
>
> You can't use a list as a key, but you can use a tuple as a key,
> provided that the elements of the tuple are also immutable.
>
> >  if (
> >  abs(sum_key_arr - key) <= 50
> >  ):  # threshold is great here so that all values are
> > approximated!
> >  # print('approximated')
> >  return cache[key]
> >  else:
> >  # print('not approximated')
> >  cache[sum_key_arr] = f(args[0], args[1])
> >  return cache[sum_key_arr]
> >
> >  return g
> >
> >
> > @memoize
> > def aggregate(dict_list_arr, operation):
> >  if operation == "avg":
> >  return sum(list(dict_list_arr)) / len(list(dict_list_arr))
> >  if operation == "sum":
> >  return sum(list(dict_list_arr))
> >  return None
> >
> >
> > t = time.time()
> > for i in range(200, 15000):
> >  res = aggregate(list(range(i)), "avg")
> >
> > elapsed = time.time() - t
> > print(res)
> > print(elapsed)
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can you help me with this memoization simple example?

2024-03-30 Thread MRAB via Python-list

On 2024-03-31 00:09, marc nicole via Python-list wrote:

I am creating a memoization example with a function that adds up / averages
the elements of an array and compares it with the cached ones to retrieve
them in case they are already stored.

In addition, I want to store only if the result of the function differs
considerably (passes a threshold e.g. 50 below).

I created an example using a decorator to do so, the results using the
decorator is slightly faster than without the memoization which is OK, but
is the logic of the decorator correct ? anybody can tell me ?

My code is attached below:



import time


def memoize(f):
 cache = {}

 def g(*args):
 if args[1] == "avg":
 sum_key_arr = sum(list(args[0])) / len(list(args[0]))


'list' will iterate over args[0] to make a list, and 'sum' will iterate 
over that list.


It would be simpler to just let 'sum' iterate over args[0].


 elif args[1] == "sum":
 sum_key_arr = sum(list(args[0]))
 if sum_key_arr not in cache:
 for (
 key,
 value,
 ) in (
 cache.items()
 ):  # key in dict cannot be an array so I use the sum of the
array as the key


You can't use a list as a key, but you can use a tuple as a key, 
provided that the elements of the tuple are also immutable.



 if (
 abs(sum_key_arr - key) <= 50
 ):  # threshold is great here so that all values are
approximated!
 # print('approximated')
 return cache[key]
 else:
 # print('not approximated')
 cache[sum_key_arr] = f(args[0], args[1])
 return cache[sum_key_arr]

 return g


@memoize
def aggregate(dict_list_arr, operation):
 if operation == "avg":
 return sum(list(dict_list_arr)) / len(list(dict_list_arr))
 if operation == "sum":
 return sum(list(dict_list_arr))
 return None


t = time.time()
for i in range(200, 15000):
 res = aggregate(list(range(i)), "avg")

elapsed = time.time() - t
print(res)
print(elapsed)



--
https://mail.python.org/mailman/listinfo/python-list


Can you help me with this memoization simple example?

2024-03-30 Thread marc nicole via Python-list
I am creating a memoization example with a function that adds up / averages
the elements of an array and compares it with the cached ones to retrieve
them in case they are already stored.

In addition, I want to store only if the result of the function differs
considerably (passes a threshold e.g. 50 below).

I created an example using a decorator to do so, the results using the
decorator is slightly faster than without the memoization which is OK, but
is the logic of the decorator correct ? anybody can tell me ?

My code is attached below:



import time


def memoize(f):
cache = {}

def g(*args):
if args[1] == "avg":
sum_key_arr = sum(list(args[0])) / len(list(args[0]))
elif args[1] == "sum":
sum_key_arr = sum(list(args[0]))
if sum_key_arr not in cache:
for (
key,
value,
) in (
cache.items()
):  # key in dict cannot be an array so I use the sum of the
array as the key
if (
abs(sum_key_arr - key) <= 50
):  # threshold is great here so that all values are
approximated!
# print('approximated')
return cache[key]
else:
# print('not approximated')
cache[sum_key_arr] = f(args[0], args[1])
return cache[sum_key_arr]

return g


@memoize
def aggregate(dict_list_arr, operation):
if operation == "avg":
return sum(list(dict_list_arr)) / len(list(dict_list_arr))
if operation == "sum":
return sum(list(dict_list_arr))
return None


t = time.time()
for i in range(200, 15000):
res = aggregate(list(range(i)), "avg")

elapsed = time.time() - t
print(res)
print(elapsed)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can u help me?

2024-03-06 Thread Grant Edwards via Python-list
On 2024-03-06, MRAB via Python-list  wrote:
> On 2024-03-06 01:44, Ethan Furman via Python-list wrote:
>> On 3/5/24 16:49, MRAB via Python-list wrote:
>>   > On 2024-03-06 00:24, Ethan Furman via Python-list wrote:
>>   >> On 3/5/24 16:06, Chano Fucks via Python-list wrote:
>>   >>
>>   >>> [image: image.png]
>>   >>
>>   >> The image is of MS-Windows with the python installation window of 
>> "Repair Successful".  Hopefully somebody better at
>>   >> explaining that problem can take it from here...
>>   >>
>>   > If the repair was successful, what's the problem?
>> 
>> I imagine the issue is trying get Python to run (as I recall, the python 
>> icon on the MS-Windows desktop is the
>> installer, not Python itself).
>
> There was an issue 3 years ago about renaming the installer for clarity:
>
> https://github.com/python/cpython/issues/87322

Yea, this problem comes up constantly (and has for many years).

People have suggested renaming the installer so it has "setup" or
"install" in the name.

People have suggested adding text to the installer splash screen to
explain that it's the installer and not python itself, that you
already have python installed, and if you want to _run_ python instead
of _install_ python, here's how.

People have suggested having the installer remove itself by default
when it's done installing.

People have suggested lots of solutions.

AFAICT, nobody has actually done anything.


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can u help me?

2024-03-05 Thread MRAB via Python-list

On 2024-03-06 01:44, Ethan Furman via Python-list wrote:

On 3/5/24 16:49, MRAB via Python-list wrote:
  > On 2024-03-06 00:24, Ethan Furman via Python-list wrote:
  >> On 3/5/24 16:06, Chano Fucks via Python-list wrote:
  >>
  >>> [image: image.png]
  >>
  >> The image is of MS-Windows with the python installation window of "Repair 
Successful".  Hopefully somebody better at
  >> explaining that problem can take it from here...
  >>
  > If the repair was successful, what's the problem?

I imagine the issue is trying get Python to run (as I recall, the python icon 
on the MS-Windows desktop is the
installer, not Python itself).


There was an issue 3 years ago about renaming the installer for clarity:

https://github.com/python/cpython/issues/87322

--
https://mail.python.org/mailman/listinfo/python-list


Re: Can u help me?

2024-03-05 Thread Mats Wichmann via Python-list

On 3/5/24 18:44, Ethan Furman via Python-list wrote:

On 3/5/24 16:49, MRAB via Python-list wrote:
 > On 2024-03-06 00:24, Ethan Furman via Python-list wrote:
 >> On 3/5/24 16:06, Chano Fucks via Python-list wrote:
 >>
 >>> [image: image.png]
 >>
 >> The image is of MS-Windows with the python installation window of 
"Repair Successful".  Hopefully somebody better at

 >> explaining that problem can take it from here...
 >>
 > If the repair was successful, what's the problem?

I imagine the issue is trying get Python to run (as I recall, the python 
icon on the MS-Windows desktop is the installer, not Python itself).


that's often it, yes - you keep getting the installer when you think you 
should get a snazzy Python window. Of course, you don't - Python is a 
command-line/terminal program, not a windows app.  Now if you tried to 
launch IDLE instead, you'd get at least a window.


But we're just guessing here. Perhaps Chano will come back with an 
updated question with some details.

--
https://mail.python.org/mailman/listinfo/python-list


Re: Can u help me?

2024-03-05 Thread Ethan Furman via Python-list

On 3/5/24 16:49, MRAB via Python-list wrote:
> On 2024-03-06 00:24, Ethan Furman via Python-list wrote:
>> On 3/5/24 16:06, Chano Fucks via Python-list wrote:
>>
>>> [image: image.png]
>>
>> The image is of MS-Windows with the python installation window of "Repair 
Successful".  Hopefully somebody better at
>> explaining that problem can take it from here...
>>
> If the repair was successful, what's the problem?

I imagine the issue is trying get Python to run (as I recall, the python icon on the MS-Windows desktop is the 
installer, not Python itself).

--
https://mail.python.org/mailman/listinfo/python-list


Re: Can u help me?

2024-03-05 Thread MRAB via Python-list

On 2024-03-06 00:24, Ethan Furman via Python-list wrote:

On 3/5/24 16:06, Chano Fucks via Python-list wrote:


[image: image.png]


The image is of MS-Windows with the python installation window of "Repair 
Successful".  Hopefully somebody better at
explaining that problem can take it from here...


If the repair was successful, what's the problem?
--
https://mail.python.org/mailman/listinfo/python-list


Re: Can u help me?

2024-03-05 Thread MRAB via Python-list

On 2024-03-06 00:06, Chano Fucks via Python-list wrote:

[image: image.png]


This list removes all images.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Can u help me?

2024-03-05 Thread Ethan Furman via Python-list

On 3/5/24 16:06, Chano Fucks via Python-list wrote:


[image: image.png]


The image is of MS-Windows with the python installation window of "Repair Successful".  Hopefully somebody better at 
explaining that problem can take it from here...


--
~Ethan~
--
https://mail.python.org/mailman/listinfo/python-list


Can u help me?

2024-03-05 Thread Chano Fucks via Python-list
[image: image.png]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Fwd: Can you help me with this Python question?

2022-10-13 Thread Axy via Python-list
Well, although I never used pandas and never will, if that's about 
artworks, that's mine.


Obviously, you need to iterate columns and sum values returned by the 
snippet you provided. A quick search tells us to use colums property. 
So, it might look like this:


na_sum = sum(df[name].isnull().sum() for name in df.columns)

Axy

On 13/10/2022 13:44, Sarah Wallace wrote:

For a python class I am taking..

In this challenge, you'll be working with a DataFrame that contains data
about artworks, and it contains many missing values.

Your task is to create a variable called na_sum that contains the total
number of missing values in the DataFrame. When that's completed, print out
your answer!

Hint: The code given below will give you the number of missing (NaN) values
for the *Name* column in the DataFrame. How would you edit the code to get
the missing values for every column in the DataFrame?
Extra hint: You'll be returning a single number which is the final sum() of
everything.

df['Name'].isnull().sum()


--
https://mail.python.org/mailman/listinfo/python-list


Fwd: Can you help me with this Python question?

2022-10-13 Thread Sarah Wallace
For a python class I am taking..

In this challenge, you'll be working with a DataFrame that contains data
about artworks, and it contains many missing values.

Your task is to create a variable called na_sum that contains the total
number of missing values in the DataFrame. When that's completed, print out
your answer!

Hint: The code given below will give you the number of missing (NaN) values
for the *Name* column in the DataFrame. How would you edit the code to get
the missing values for every column in the DataFrame?
Extra hint: You'll be returning a single number which is the final sum() of
everything.

df['Name'].isnull().sum()

-- 
Thanks!

*Sarah Wallace*
sarah.wallac...@gmail.com




-- 
Thanks!

*Sarah Wallace*
sarah.wallac...@gmail.com
214.300.1064
-- 
https://mail.python.org/mailman/listinfo/python-list


Is the bug reported to python Recently i upgraded my python version and its directory But when i try to download pyqt5 it gives out a holy error Do i have to install py 3.9 again pls help me take a lo

2021-10-17 Thread Umme Salma


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help me split a string into elements

2021-09-04 Thread Neil
DFS  wrote:
> Typical cases:
>  lines = [('one\ntwo\nthree\n')]
>  print(str(lines[0]).splitlines())
>  ['one', 'two', 'three']
> 
>  lines = [('one two three\n')]
>  print(str(lines[0]).split())
>  ['one', 'two', 'three']
> 
> 
> That's the result I'm wanting, but I get data in a slightly different 
> format:
> 
> lines = [('one\ntwo\nthree\n',)]
> 
> Note the comma after the string data, but inside the paren. 
> splitlines() doesn't work on it:
> 
> print(str(lines[0]).splitlines())
> ["('one\\ntwo\\nthree\\n',)"]
> 
> 
> I've banged my head enough - can someone spot an easy fix?
> 
> Thanks

lines[0][0].splitlines()

(You have a list containing a tuple containing the string you want to
split up.)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help me split a string into elements

2021-09-04 Thread DFS

On 9/4/2021 5:55 PM, DFS wrote:

Typical cases:
  lines = [('one\ntwo\nthree\n')]
  print(str(lines[0]).splitlines())
  ['one', 'two', 'three']

  lines = [('one two three\n')]
  print(str(lines[0]).split())
  ['one', 'two', 'three']


That's the result I'm wanting, but I get data in a slightly different 
format:


lines = [('one\ntwo\nthree\n',)]

Note the comma after the string data, but inside the paren. splitlines() 
doesn't work on it:


print(str(lines[0]).splitlines())
["('one\\ntwo\\nthree\\n',)"]


I've banged my head enough - can someone spot an easy fix?

Thanks



I got it:

lines = [('one\ntwo\nthree\n',)]
print(str(lines[0][0]).splitlines())
['one', 'two', 'three']

--
https://mail.python.org/mailman/listinfo/python-list


Help me split a string into elements

2021-09-04 Thread DFS

Typical cases:
 lines = [('one\ntwo\nthree\n')]
 print(str(lines[0]).splitlines())
 ['one', 'two', 'three']

 lines = [('one two three\n')]
 print(str(lines[0]).split())
 ['one', 'two', 'three']


That's the result I'm wanting, but I get data in a slightly different 
format:


lines = [('one\ntwo\nthree\n',)]

Note the comma after the string data, but inside the paren. 
splitlines() doesn't work on it:


print(str(lines[0]).splitlines())
["('one\\ntwo\\nthree\\n',)"]


I've banged my head enough - can someone spot an easy fix?

Thanks
--
https://mail.python.org/mailman/listinfo/python-list


Re: help me please. "install reppy"

2021-07-23 Thread Jack DeVries
See here for a discussion around this issue:
https://github.com/seomoz/reppy/issues/90

This project requires a C++ build environment to be setup on your computer.
The fact that your compiler is reporting that `std=c++11` as an unknown
option shows that you don't have a C++ build environment set up. As you
will see, at the end of the issue above, they link to this issue:

https://github.com/Benny-/Yahoo-ticker-symbol-downloader/issues/46

In that second issue, a user reports:
> hey all. I solved the issue by installing Build tools for visual c++ 2015
(v14). The link does not work.
> You have to look for build tools for visual studio 2017 (v15) and look at
the options in the installer.

As a side note, you might consider using this robots.txt parser from the
standard library instead. It's already installed and ready to go, and
doesn't use very-overkill C++ dependencies!

Good luck!


On Thu, Jul 22, 2021 at 8:44 PM たこしたこし  wrote:

> I get an error so please help.
> I don't know what to do.
>
> Windows 10
> Python 3.9.6
>
> from takashi in Japan
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help me please. "install reppy"

2021-07-23 Thread Jack DeVries
Oops, forgot the link to the standard library robots.txt parser. Here are
the docs!


https://docs.python.org/3/library/urllib.robotparser.html

*sorry for the noise*

On Thu, Jul 22, 2021 at 11:34 PM Jack DeVries 
wrote:

> See here for a discussion around this issue:
> https://github.com/seomoz/reppy/issues/90
>
> This project requires a C++ build environment to be setup on your
> computer. The fact that your compiler is reporting that `std=c++11` as an
> unknown option shows that you don't have a C++ build environment set up. As
> you will see, at the end of the issue above, they link to this issue:
>
> https://github.com/Benny-/Yahoo-ticker-symbol-downloader/issues/46
>
> In that second issue, a user reports:
> > hey all. I solved the issue by installing Build tools for visual c++
> 2015 (v14). The link does not work.
> > You have to look for build tools for visual studio 2017 (v15) and look
> at the options in the installer.
>
> As a side note, you might consider using this robots.txt parser from the
> standard library instead. It's already installed and ready to go, and
> doesn't use very-overkill C++ dependencies!
>
> Good luck!
>
>
> On Thu, Jul 22, 2021 at 8:44 PM たこしたこし  wrote:
>
>> I get an error so please help.
>> I don't know what to do.
>>
>> Windows 10
>> Python 3.9.6
>>
>> from takashi in Japan
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>>
>
-- 
https://mail.python.org/mailman/listinfo/python-list


help me please. "install reppy"

2021-07-22 Thread たこしたこし
I get an error so please help.
I don't know what to do.

Windows 10
Python 3.9.6

from takashi in Japan
Microsoft Windows [Version 10.0.19042.1110]
(c) Microsoft Corporation. All rights reserved.

C:\Users\user>pip3 install reppy
Looking in indexes: https://pypi.python.org/simple/
Collecting reppy
  Using cached reppy-0.4.14.tar.gz (93 kB)
Requirement already satisfied: cachetools in 
c:\users\user\appdata\local\programs\python\python39\lib\site-packages (from 
reppy) (4.2.2)
Requirement already satisfied: python-dateutil!=2.0,>=1.5 in 
c:\users\user\appdata\local\programs\python\python39\lib\site-packages (from 
reppy) (2.8.1)
Requirement already satisfied: requests in 
c:\users\user\appdata\local\programs\python\python39\lib\site-packages (from 
reppy) (2.25.1)
Requirement already satisfied: six in 
c:\users\user\appdata\local\programs\python\python39\lib\site-packages (from 
reppy) (1.16.0)
Requirement already satisfied: idna<3,>=2.5 in 
c:\users\user\appdata\local\programs\python\python39\lib\site-packages (from 
requests->reppy) (2.10)
Requirement already satisfied: certifi>=2017.4.17 in 
c:\users\user\appdata\local\programs\python\python39\lib\site-packages (from 
requests->reppy) (2021.5.30)
Requirement already satisfied: chardet<5,>=3.0.2 in 
c:\users\user\appdata\local\programs\python\python39\lib\site-packages (from 
requests->reppy) (4.0.0)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in 
c:\users\user\appdata\local\programs\python\python39\lib\site-packages (from 
requests->reppy) (1.26.6)
Building wheels for collected packages: reppy
  Building wheel for reppy (setup.py) ... error
  ERROR: Command errored out with exit status 1:
   command: 'c:\users\user\appdata\local\programs\python\python39\python.exe' 
-u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = 
'"'"'C:\\Users\\user\\AppData\\Local\\Temp\\pip-install-sjlk_02k\\reppy_2f114414e650471d8c3902d5b364a96c\\setup.py'"'"';
 
__file__='"'"'C:\\Users\\user\\AppData\\Local\\Temp\\pip-install-sjlk_02k\\reppy_2f114414e650471d8c3902d5b364a96c\\setup.py'"'"';f
 = getattr(tokenize, '"'"'open'"'"', open)(__file__) if 
os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; 
setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', 
'"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' 
bdist_wheel -d 'C:\Users\user\AppData\Local\Temp\pip-wheel-pcr61ilh'
   cwd: 
C:\Users\user\AppData\Local\Temp\pip-install-sjlk_02k\reppy_2f114414e650471d8c3902d5b364a96c\
  Complete output (69 lines):
  Building from C++
  
c:\users\user\appdata\local\programs\python\python39\lib\site-packages\setuptools\dist.py:697:
 UserWarning: Usage of dash-separated 'description-file' will not be supported 
in future versions. Please use the underscore name 'description_file' instead
warnings.warn(
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build\lib.win-amd64-3.9
  creating build\lib.win-amd64-3.9\reppy
  copying reppy\exceptions.py -> build\lib.win-amd64-3.9\reppy
  copying reppy\ttl.py -> build\lib.win-amd64-3.9\reppy
  copying reppy\util.py -> build\lib.win-amd64-3.9\reppy
  copying reppy\__init__.py -> build\lib.win-amd64-3.9\reppy
  creating build\lib.win-amd64-3.9\reppy\cache
  copying reppy\cache\policy.py -> build\lib.win-amd64-3.9\reppy\cache
  copying reppy\cache\__init__.py -> build\lib.win-amd64-3.9\reppy\cache
  running build_ext
  building 'reppy.robots' extension
  creating build\temp.win-amd64-3.9
  creating build\temp.win-amd64-3.9\Release
  creating build\temp.win-amd64-3.9\Release\reppy
  creating build\temp.win-amd64-3.9\Release\reppy\rep-cpp
  creating build\temp.win-amd64-3.9\Release\reppy\rep-cpp\deps
  creating build\temp.win-amd64-3.9\Release\reppy\rep-cpp\deps\url-cpp
  creating build\temp.win-amd64-3.9\Release\reppy\rep-cpp\deps\url-cpp\src
  creating build\temp.win-amd64-3.9\Release\reppy\rep-cpp\src
  C:\Program Files (x86)\Microsoft Visual 
Studio\2019\Community\VC\Tools\MSVC\14.29.30037\bin\HostX86\x64\cl.exe /c 
/nologo /Ox /W3 /GL /DNDEBUG /MD -Ireppy/rep-cpp/include 
-Ireppy/rep-cpp/deps/url-cpp/include 
-Ic:\users\user\appdata\local\programs\python\python39\include 
-Ic:\users\user\appdata\local\programs\python\python39\include -IC:\Program 
Files (x86)\Microsoft Visual 
Studio\2019\Community\VC\Tools\MSVC\14.29.30037\ATLMFC\include -IC:\Program 
Files (x86)\Microsoft Visual 
Studio\2019\Community\VC\Tools\MSVC\14.29.30037\include -IC:\Program Files 
(x86)\Windows Kits\NETFXSDK\4.8\include\um -IC:\Program Files (x86)\Windows 
Kits\10\include\10.0.19041.0\ucrt -IC:\Program Files (x86)\Windows 
Kits\10\include\10.0.19041.0\shared -IC:\Program Files (x86)\Windows 
Kits\10\include\10.0.19041.0\um -IC:\Program Files (x86)\Windows 
Kits\10\include\10.0.19041.0\winrt -IC:\Program Files (x86)\Windows 
Kits\10\include\10.0.19041.0\cppwinrt /EHsc 
/Tpreppy/rep-cpp/deps/url-cpp/src/psl.cpp 

Help me in setting the path in python program.

2021-06-07 Thread Maheshwari Gorle
I am using Google co lab. 
Guide me how to set the path. 
# Error: SwissEph file 'se13681s.se1' not found in PATH '/usr/share/ephe/' is 
coming, how to overcome this problem.

pip install pyswisseph
import swisseph as swe
swe.set_ephe_path ('/usr/share/ephe') 
# set path to ephemeris files
jd = swe.julday(2008,3,21)
swe.calc_ut(jd, swe.AST_OFFSET+13681[0][0] 
-- 
https://mail.python.org/mailman/listinfo/python-list


How to convert csv to netcdf please help me python users

2020-05-29 Thread kotichowdary28
Hi all

I hope all are  doing well

please help me how to convert CSV to NetCDF. Im trying but its not working


#!/usr/bin/env ipython
import pandas as pd
import numpy as np
import netCDF4
import pandas as pd
import xarray as xr


stn_precip='ts_sept.csv'
orig_precip='ts_sept.csv'
stations = pd.read_csv(stn_precip)

stncoords = stations.iloc[:]
orig = pd.read_csv(orig_precip)
lats = stncoords['latitude']
lons = stncoords['longitude']
nstations = np.size(lons)
ncout = netCDF4.Dataset('Precip_1910-2018_homomod.nc', 'w')

ncout.createDimension('station',nstations)
ncout.createDimension('time',orig.shape[0])

lons_out = lons.tolist()
lats_out = lats.tolist()
time_out = orig.index.tolist()

lats = ncout.createVariable('latitude',np.dtype('float32').char,('station',))
lons = ncout.createVariable('longitude',np.dtype('float32').char,('station',))
time = ncout.createVariable('time',np.dtype('float32').char,('time',))
precip = ncout.createVariable('precip',np.dtype('float32').char,('time', 
'station'))

lats[:] = lats_out
lons[:] = lons_out
time[:] = time_out
precip[:] = orig
ncout.close()

 

-- 
https://mail.python.org/mailman/listinfo/python-list


please help me while installing pyttsx3 it shows error

2020-04-27 Thread AMAN BHAI PATEL
PS C:\Users\amanb\OneDrive\Desktop\jarvis> pip install pyttsx3
Collecting pyttsx3
  Using cached pyttsx3-2.87-py3-none-any.whl (39 kB)
Collecting comtypes; platform_system == "Windows"
  Using cached comtypes-1.1.7.zip (180 kB)
Installing collected packages: comtypes, pyttsx3
Running setup.py install for comtypes ... error
ERROR: Command errored out with exit status 1:
 command: 
'C:\Users\amanb\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\python.exe'
 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = 
'"'"'C:\\Users\\amanb\\AppData\\Local\\Temp\\pip-install-uwazge93\\comtypes\\setup.py'"'"';
 
__file__='"'"'C:\\Users\\amanb\\AppData\\Local\\Temp\\pip-install-uwazge93\\comtypes\\setup.py'"'"';f=getattr(tokenize,
 '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', 
'"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install 
--record 
'C:\Users\amanb\AppData\Local\Temp\pip-record-3lktlb2m\install-record.txt' 
--single-version-externally-managed 
--user --prefix= --compile --install-headers 
'C:\Users\amanb\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\Include\comtypes'
 cwd: C:\Users\amanb\AppData\Local\Temp\pip-install-uwazge93\comtypes\
Complete output (276 lines):
running install
running build
running build_py
creating build
creating build\lib
creating build\lib\comtypes
copying comtypes\automation.py -> build\lib\comtypes
copying comtypes\connectionpoints.py -> build\lib\comtypes
copying comtypes\errorinfo.py -> build\lib\comtypes
copying comtypes\git.py -> build\lib\comtypes
copying comtypes\GUID.py -> build\lib\comtypes
copying comtypes\hresult.py -> build\lib\comtypes
copying comtypes\logutil.py -> build\lib\comtypes
copying comtypes\messageloop.py -> build\lib\comtypes
copying comtypes\npsupport.py -> build\lib\comtypes
copying comtypes\patcher.py -> build\lib\comtypes
copying comtypes\persist.py -> build\lib\comtypes
copying comtypes\safearray.py -> build\lib\comtypes
copying comtypes\shelllink.py -> build\lib\comtypes
copying comtypes\typeinfo.py -> build\lib\comtypes
copying comtypes\util.py -> build\lib\comtypes
copying comtypes\viewobject.py -> build\lib\comtypes
copying comtypes\_comobject.py -> build\lib\comtypes
copying comtypes\_meta.py -> build\lib\comtypes
copying comtypes\_safearray.py -> build\lib\comtypes
copying comtypes\__init__.py -> build\lib\comtypes
creating build\lib\comtypes\client
copying comtypes\client\dynamic.py -> build\lib\comtypes\client
copying comtypes\client\lazybind.py -> build\lib\comtypes\client
copying comtypes\client\_code_cache.py -> build\lib\comtypes\client
copying comtypes\client\_events.py -> build\lib\comtypes\client
copying comtypes\client\_generate.py -> build\lib\comtypes\client
copying comtypes\client\__init__.py -> build\lib\comtypes\client
creating build\lib\comtypes\server
copying comtypes\server\automation.py -> build\lib\comtypes\server
copying comtypes\server\connectionpoints.py -> build\lib\comtypes\server
copying comtypes\server\inprocserver.py -> build\lib\comtypes\server
copying comtypes\server\localserver.py -> build\lib\comtypes\server
copying comtypes\server\register.py -> build\lib\comtypes\server
copying comtypes\server\w_getopt.py -> build\lib\comtypes\server
copying comtypes\server\__init__.py -> build\lib\comtypes\server
creating build\lib\comtypes\tools
copying comtypes\tools\codegenerator.py -> build\lib\comtypes\tools
copying comtypes\tools\tlbparser.py -> build\lib\comtypes\tools
copying comtypes\tools\typedesc.py -> build\lib\comtypes\tools
copying comtypes\tools\typedesc_base.py -> build\lib\comtypes\tools
copying comtypes\tools\__init__.py -> build\lib\comtypes\tools
creating build\lib\comtypes\test
copying comtypes\test\find_memleak.py -> build\lib\comtypes\test
copying comtypes\test\runtests.py -> build\lib\comtypes\test
copying comtypes\test\setup.py -> build\lib\comtypes\test
copying comtypes\test\TestComServer.py -> build\lib\comtypes\test
copying comtypes\test\TestDispServer.py -> build\lib\comtypes\test
copying comtypes\test\test_agilent.py -> build\lib\comtypes\test
copying comtypes\test\test_avmc.py -> build\lib\comtypes\test
copying comtypes\test\test_basic.py -> build\lib\comtypes\test
copying comtypes\test\test_BSTR.py -> build\lib\comtypes\test
copying comtypes\test\test_casesensitivity.py -> build\lib\comtypes\test
copying comtypes\test\test_client.py -> build\lib\comtypes\test
copying comtypes\test\test_collections.py -> build\lib\comtypes\test
copying comtypes\test\test_comserver.py -> build\lib\comtypes\test
copying comtypes\test\test_createwrappers.py -> build\lib\comtypes\test
copying 

Re: help me subcorrect

2020-04-11 Thread Souvik Dutta
Did you send a screenshot? If so then understand that this mailing list
does not support photos so you cannot send that. Try giving us a verbal
description. And if you write anything other that the sub then sorry that
is my Gmail's fault.

Souvik flutter dev

On Sat, Apr 11, 2020, 8:32 PM khuchee  wrote:

>
>
> Sent from Mail for Windows 10
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


help me subcorrect

2020-04-11 Thread khuchee



Sent from Mail for Windows 10

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can you help me solve this?

2020-03-16 Thread Pieter van Oostrum
Pieter van Oostrum  writes:

> Joseph Nail  writes:
>
>> Hello,
>> I have one problem. Somehow in my function when I wrote y=x, they are the
>> same variable and then it also changes age or height (which were x) in the
>> main program. See more in attached file.
>> Maybe it is bug or maybe it should run that way.
>
> If you write y = x, then they are not the same variable, but they point
> to (the proper Python language is they are bound to) the same object.
>
> Now if you say x.age = 20, then y.age will also be 20 (it's the same object).

If you want y to be an independent copy of x (i.e. a new object that has the 
same values), use:

import copy
y = copy.copy(x)

Now you can change x.age and it won't affect y.age
-- 
Pieter van Oostrum
www: http://pieter.vanoostrum.org/
PGP key: [8DAE142BE17999C4]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can you help me solve this?

2020-03-16 Thread Pieter van Oostrum
Joseph Nail  writes:

> Hello,
> I have one problem. Somehow in my function when I wrote y=x, they are the
> same variable and then it also changes age or height (which were x) in the
> main program. See more in attached file.
> Maybe it is bug or maybe it should run that way.

If you write y = x, then they are not the same variable, but they point to (the 
proper Python language is they are bound to) the same object.

Now if you say x.age = 20, then y.age will also be 20 (it's the same object).
-- 
Pieter van Oostrum
www: http://pieter.vanoostrum.org/
PGP key: [8DAE142BE17999C4]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can you help me solve this?

2020-03-16 Thread Igor Korot
Hi,

On Mon, Mar 16, 2020 at 4:26 PM Joseph Nail  wrote:
>
> Hello,
> I have one problem. Somehow in my function when I wrote y=x, they are the
> same variable and then it also changes age or height (which were x) in the
> main program. See more in attached file.
> Maybe it is bug or maybe it should run that way.

This is the text only ML -> NO ATTACHMENT.

Please copy and paste the code inside the E-mail body send it out.

Thank you,

> --
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Can you help me solve this?

2020-03-16 Thread Joseph Nail
Hello,
I have one problem. Somehow in my function when I wrote y=x, they are the
same variable and then it also changes age or height (which were x) in the
main program. See more in attached file.
Maybe it is bug or maybe it should run that way.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help me fix a problem

2019-09-06 Thread Spencer Du
On Friday, 6 September 2019 20:15:40 UTC+2, MRAB  wrote:
> On 2019-09-06 18:11, Spencer Du wrote:
> > Hi
> > 
> > I want to print yes in gui.py but it does not get printed because of the 
> > json. How do I fix this. Execute embedded.py and then gui.py to test.
> > 
> > def on_message(client, userdata, msg):
> > print("message recieved= " + msg.payload.decode())
> > # print("File which you want to import(with .py extension)")
> > print("message topic=", msg.topic)
> > print("message qos=", msg.qos)
> > print("message retain flag=", msg.retain)
> > 
>  >if msg.payload[name] == "Hello world!":
>  >print("Yes!")
>  >
> What is the value of the variable called 'name'? Or did you intend that 
> to be a string?
> 
>   if msg.payload["name"] == "Hello world!":
>   print("Yes!")

"name" is part of {"name": "Hello world!"} which is a key value pair dictionary 
and json.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help me fix a problem

2019-09-06 Thread Spencer Du
On Friday, 6 September 2019 20:15:40 UTC+2, MRAB  wrote:
> On 2019-09-06 18:11, Spencer Du wrote:
> > Hi
> > 
> > I want to print yes in gui.py but it does not get printed because of the 
> > json. How do I fix this. Execute embedded.py and then gui.py to test.
> > 
> > def on_message(client, userdata, msg):
> > print("message recieved= " + msg.payload.decode())
> > # print("File which you want to import(with .py extension)")
> > print("message topic=", msg.topic)
> > print("message qos=", msg.qos)
> > print("message retain flag=", msg.retain)
> > 
>  >if msg.payload[name] == "Hello world!":
>  >print("Yes!")
>  >
> What is the value of the variable called 'name'? Or did you intend that 
> to be a string?
> 
>   if msg.payload["name"] == "Hello world!":
>   print("Yes!")


{"name": "Hello world!"} is a key value pair.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help me fix a problem

2019-09-06 Thread Spencer Du
On Friday, 6 September 2019 20:15:40 UTC+2, MRAB  wrote:
> On 2019-09-06 18:11, Spencer Du wrote:
> > Hi
> > 
> > I want to print yes in gui.py but it does not get printed because of the 
> > json. How do I fix this. Execute embedded.py and then gui.py to test.
> > 
> > def on_message(client, userdata, msg):
> > print("message recieved= " + msg.payload.decode())
> > # print("File which you want to import(with .py extension)")
> > print("message topic=", msg.topic)
> > print("message qos=", msg.qos)
> > print("message retain flag=", msg.retain)
> > 
>  >if msg.payload[name] == "Hello world!":
>  >print("Yes!")
>  >
> What is the value of the variable called 'name'? Or did you intend that 
> to be a string?
> 
>   if msg.payload["name"] == "Hello world!":
>   print("Yes!")
"name" is part of {"name": "Hello world!"} which is a key value pair dictionary 
json.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help me fix a problem

2019-09-06 Thread MRAB

On 2019-09-06 18:11, Spencer Du wrote:

Hi

I want to print yes in gui.py but it does not get printed because of the json. 
How do I fix this. Execute embedded.py and then gui.py to test.

def on_message(client, userdata, msg):
print("message recieved= " + msg.payload.decode())
# print("File which you want to import(with .py extension)")
print("message topic=", msg.topic)
print("message qos=", msg.qos)
print("message retain flag=", msg.retain)


>if msg.payload[name] == "Hello world!":
>print("Yes!")
>
What is the value of the variable called 'name'? Or did you intend that 
to be a string?


if msg.payload["name"] == "Hello world!":
print("Yes!")
--
https://mail.python.org/mailman/listinfo/python-list


Help me fix a problem

2019-09-06 Thread Spencer Du
Hi 

I want to print yes in gui.py but it does not get printed because of the json. 
How do I fix this. Execute embedded.py and then gui.py to test.

embedded.py

import paho.mqtt.client as mqtt
from mqtt import *

client = mqtt.Client()
client.connect("broker.hivemq.com",1883,60)

client.on_connect = on_connect
client.subscribe("topic/test")
client.on_subscribe = on_subscribe
print("Subscribing to topic", "topic/test")
client.on_message = on_message

client.loop_forever()

gui.py

import paho.mqtt.client as mqtt
from mqtt import *
import json

# This is the Publisher

client = mqtt.Client()
client.connect("broker.hivemq.com",1883,60)
print("Publishing message (name: Hello world!) to topic", "topic/test")
client.publish("topic/test",json.dumps({"name": "Hello world!"}));
client.loop_forever();

mqtt.py

import logging
import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
print("Connecting to broker")
# client.subscribe("topic/test")

def on_subscribe(client, userdata, mid, granted_qos):
print("I've subscribed to topic")

def on_message(client, userdata, msg):
print("message recieved= " + msg.payload.decode())
# print("File which you want to import(with .py extension)")
print("message topic=", msg.topic)
print("message qos=", msg.qos)
print("message retain flag=", msg.retain)

if msg.payload[name] == "Hello world!":
print("Yes!")

Regards 
Spencer
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Please help me

2019-08-06 Thread Brian Oney via Python-list
On Mon, 2019-08-05 at 21:10 +0430, arash kohansal wrote:
> Hello ive just installed python on my pc and ive already check the
> path
> choice part but microsoft visual code can not find it and it does not
> have
> the reload item

Check out: https://code.visualstudio.com/docs/languages/python

or

https://realpython.com/python-development-visual-studio-code/

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Please help me

2019-08-05 Thread MRAB

On 2019-08-05 17:40, arash kohansal wrote:

Hello ive just installed python on my pc and ive already check the path
choice part but microsoft visual code can not find it and it does not have
the reload item


1. Open Visual Studio Code.

2. Press F1, type "Python: Select Interpreter", and then press Enter.

3. Select the Python version that you installed from the list.
--
https://mail.python.org/mailman/listinfo/python-list


Please help me

2019-08-05 Thread arash kohansal
Hello ive just installed python on my pc and ive already check the path
choice part but microsoft visual code can not find it and it does not have
the reload item
-- 
https://mail.python.org/mailman/listinfo/python-list


Can someone help me paral/accelerate this code for Cuda?

2019-05-15 Thread amoxletne5
It’s pretty darn slow. I don’t think it’s optimizing the Nvidia Tesla v100 
power. It uses some openCv , and it just screams for paral/acceleration. I’d 
also love to learn and see how it’s done

import cv2
import numpy as np
import os
import pickle
import sys
from cgls import cgls
from filterplot import filterplot
from gaussian2d import gaussian2d
from gettrainargs import gettrainargs
from hashkey import hashkey
from math import floor
from matplotlib import pyplot as plt
from scipy import interpolate
from skimage import transform

args = gettrainargs()

# Define parameters
R = 2
patchsize = 11
gradientsize = 9
Qangle = 24
Qstrength = 3
Qcoherence = 3
trainpath = 'train'

# Calculate the margin
maxblocksize = max(patchsize, gradientsize)
margin = floor(maxblocksize/2)
patchmargin = floor(patchsize/2)
gradientmargin = floor(gradientsize/2)

Q = np.zeros((Qangle, Qstrength, Qcoherence, R*R, patchsize*patchsize, 
patchsize*patchsize))
V = np.zeros((Qangle, Qstrength, Qcoherence, R*R, patchsize*patchsize))
h = np.zeros((Qangle, Qstrength, Qcoherence, R*R, patchsize*patchsize))

# Read Q,V from file
if args.qmatrix:
with open(args.qmatrix, "rb") as fp:
Q = pickle.load(fp)
if args.vmatrix:
with open(args.vmatrix, "rb") as fp:
V = pickle.load(fp)

# Matrix preprocessing
# Preprocessing normalized Gaussian matrix W for hashkey calculation
weighting = gaussian2d([gradientsize, gradientsize], 2)
weighting = np.diag(weighting.ravel())

# Get image list
imagelist = []
for parent, dirnames, filenames in os.walk(trainpath):
for filename in filenames:
if filename.lower().endswith(('.bmp', '.dib', '.png', '.jpg', '.jpeg', 
'.pbm', '.pgm', '.ppm', '.tif', '.tiff')):
imagelist.append(os.path.join(parent, filename))

# Compute Q and V
imagecount = 1
for image in imagelist:
print('\r', end='')
print(' ' * 60, end='')
print('\rProcessing image ' + str(imagecount) + ' of ' + 
str(len(imagelist)) + ' (' + image + ')')
origin = cv2.imread(image)
# Extract only the luminance in YCbCr
grayorigin = cv2.cvtColor(origin, cv2.COLOR_BGR2YCrCb)[:,:,0]
# Normalized to [0,1]
grayorigin = cv2.normalize(grayorigin.astype('float'), None, 
grayorigin.min()/255, grayorigin.max()/255, cv2.NORM_MINMAX)
# Downscale (bicubic interpolation)
height, width = grayorigin.shape
LR = transform.resize(grayorigin, (floor((height+1)/2),floor((width+1)/2)), 
mode='reflect', anti_aliasing=False)
# Upscale (bilinear interpolation)
height, width = LR.shape
heightgrid = np.linspace(0, height-1, height)
widthgrid = np.linspace(0, width-1, width)
bilinearinterp = interpolate.interp2d(widthgrid, heightgrid, LR, 
kind='linear')
heightgrid = np.linspace(0, height-1, height*2-1)
widthgrid = np.linspace(0, width-1, width*2-1)
upscaledLR = bilinearinterp(widthgrid, heightgrid)
# Calculate A'A, A'b and push them into Q, V
height, width = upscaledLR.shape
operationcount = 0
totaloperations = (height-2*margin) * (width-2*margin)
for row in range(margin, height-margin):
for col in range(margin, width-margin):
if round(operationcount*100/totaloperations) != 
round((operationcount+1)*100/totaloperations):
print('\r|', end='')
print('#' * round((operationcount+1)*100/totaloperations/2), 
end='')
print(' ' * (50 - 
round((operationcount+1)*100/totaloperations/2)), end='')
print('|  ' + 
str(round((operationcount+1)*100/totaloperations)) + '%', end='')
sys.stdout.flush()
operationcount += 1
# Get patch
patch = upscaledLR[row-patchmargin:row+patchmargin+1, 
col-patchmargin:col+patchmargin+1]
patch = np.matrix(patch.ravel())
# Get gradient block
gradientblock = upscaledLR[row-gradientmargin:row+gradientmargin+1, 
col-gradientmargin:col+gradientmargin+1]
# Calculate hashkey
angle, strength, coherence = hashkey(gradientblock, Qangle, 
weighting)
# Get pixel type
pixeltype = ((row-margin) % R) * R + ((col-margin) % R)
# Get corresponding HR pixel
pixelHR = grayorigin[row,col]
# Compute A'A and A'b
ATA = np.dot(patch.T, patch)
ATb = np.dot(patch.T, pixelHR)
ATb = np.array(ATb).ravel()
# Compute Q and V
Q[angle,strength,coherence,pixeltype] += ATA
V[angle,strength,coherence,pixeltype] += ATb
imagecount += 1

# Write Q,V to file
with open("q.p", "wb") as fp:
pickle.dump(Q, fp)
with open("v.p", "wb") as fp:
pickle.dump(V, fp)

# Preprocessing permutation matrices P for nearly-free 8x more learning examples
print('\r', end='')
print(' ' * 60, end='')
print('\rPreprocessing permutation matrices P for nearly-free 8x more learning 
examples ...')
sys.stdout.flush()
P = np.zeros((patchsize*patchsize, 

Re: help me in a program in python to implement Railway Reservation System using file handling technique.

2018-11-26 Thread Mario R. Osorio
On Saturday, November 24, 2018 at 1:44:21 AM UTC-5, Chris Angelico wrote:
> On Sat, Nov 24, 2018 at 5:36 PM  wrote:
> >
> > hello all,
> >  please hepl me in the above program. python to implement Railway 
> > Reservation System using file handling technique.
> >
> > System should perform below operations.
> > a. Reserve a ticket for a passenger.
> > b. List information all reservations done for today’s trains.
> 
> We won't do your homework for you. Have a shot at writing it yourself
> first, and then if you need help, bring specific questions to the
> list.
> 
> ChrisA

Specially not for an Assistant Professor at SMT.R.O.PATEL WOMEN'S MCA COLLEGE 
holding an MBA and a BCA...

Shame on you Jasmin!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help me in a program in python to implement Railway Reservation System using file handling technique.

2018-11-25 Thread Bob Gailer
On Nov 24, 2018 1:35 AM,  wrote:
>
> hello all,
>  please hepl me in the above program.

What do you mean by "the above program"? I don't see any.

python to implement Railway Reservation System using file handling
technique.
>
> System should perform below operations.
> a. Reserve a ticket for a passenger.
> b. List information all reservations done for today’s trains.
> --
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help me in a program in python to implement Railway Reservation System using file handling technique.

2018-11-25 Thread francis
On Saturday, 24 November 2018 14:33:29 UTC+8, jasmin amrutia  wrote:
> hello all,
>  please hepl me in the above program. python to implement Railway Reservation 
> System using file handling technique.
> 
> System should perform below operations.
> a. Reserve a ticket for a passenger.
> b. List information all reservations done for today’s trains.


You could get better response by offering a reward or payment.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help me in a program in python to implement Railway Reservation System using file handling technique.

2018-11-23 Thread Chris Angelico
On Sat, Nov 24, 2018 at 5:36 PM  wrote:
>
> hello all,
>  please hepl me in the above program. python to implement Railway Reservation 
> System using file handling technique.
>
> System should perform below operations.
> a. Reserve a ticket for a passenger.
> b. List information all reservations done for today’s trains.

We won't do your homework for you. Have a shot at writing it yourself
first, and then if you need help, bring specific questions to the
list.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


help me in a program in python to implement Railway Reservation System using file handling technique.

2018-11-23 Thread jasminamrutia007
hello all,
 please hepl me in the above program. python to implement Railway Reservation 
System using file handling technique.

System should perform below operations.
a. Reserve a ticket for a passenger.
b. List information all reservations done for today’s trains.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: can you please help me in opening the python programming.

2018-11-23 Thread Bob Gailer
We would be glad to help. I can't tell from your question what kind of help
you need so please give us more information.

Have you tried to install python?

If so has the installation succeeded?

What do you mean by "open the programming"?

What have you tried?

What do you expect to see?
-- 
https://mail.python.org/mailman/listinfo/python-list


can you please help me in opening the python programming.

2018-11-23 Thread hello!



Sent from Mail for Windows 10

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help me in python plssss!!!!

2018-09-14 Thread Max Zettlmeißl via Python-list
On Fri, Sep 14, 2018 at 4:33 PM, Noel P. CUA  wrote:
>  Calculate the true, relative and approximate errors, and  Relate the 
> absolute relative approximate error to the number of significant digits.
>
> epsilon = 1
>
> while epsilon + 1 > 1:
> epsilon = epsilon / 2.0
>
> epsilon = 2 * epsilon
>
> help me!
>

This list is not here to solve every single step of what is
(presumably) your homework for you. Everything you present right here
is what I helped you with in "how to convert this psuedo code to
python".
You will have to at least try it yourself and to present your
approaches or at least ideas.

Additionally, tu...@python.org seems to be more fitting for the rather
basic level of the problems which you present.
-- 
https://mail.python.org/mailman/listinfo/python-list


help me in python plssss!!!!

2018-09-14 Thread Noel P. CUA
 Calculate the true, relative and approximate errors, and  Relate the absolute 
relative approximate error to the number of significant digits.

epsilon = 1

while epsilon + 1 > 1:
epsilon = epsilon / 2.0

epsilon = 2 * epsilon

help me!

-- 

*This email and any files transmitted with it are confidential and 
intended solely for the use of the individual or entity to whom they are 
addressed. If you have received this email in error please notify the 
system manager <mailto://user...@one-bosco.org>. This message contains 
confidential information and is intended only for the individual named. *If 
you are not the named addressee you should not disseminate, distribute or 
copy this e-mail*. Please notify the sender immediately by e-mail if you 
have received this e-mail by mistake and delete this e-mail from your 
system. If you are not the intended recipient you are notified that 
disclosing, copying, distributing or taking any action in reliance on the 
contents of this information is strictly prohibited.*
-- 
https://mail.python.org/mailman/listinfo/python-list


Help me with the Python! ODE system.

2018-03-02 Thread alenkabor129769

I can not find an example with this function: 
https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.RK45.html#scipy.integrate.RK45.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help me ? (Posting On Python-List Prohibited)

2018-03-01 Thread Rustom Mody
On Thursday, March 1, 2018 at 5:37:28 AM UTC+5:30, Steven D'Aprano wrote:
> On Wed, 28 Feb 2018 09:58:24 -0800, Aktive wrote:
> 
> > what the hell do you care about cheating..
> > 
> > the world doest care about cheating.
> > 
> > its about skill.
> 
> Because cheaters don't have skill. That's why they cheat.
> 
> 
> > You guys been too much in school
> 
> Ah, spoken like a cheater.

And in case you happen to want to ‘get real’
http://www.latimes.com/opinion/op-ed/la-oe-caplan-education-credentials-20180211-story.html
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help me ? (Posting On Python-List Prohibited)

2018-02-28 Thread Steven D'Aprano
On Wed, 28 Feb 2018 09:58:24 -0800, Aktive wrote:

> what the hell do you care about cheating..
> 
> the world doest care about cheating.
> 
> its about skill.

Because cheaters don't have skill. That's why they cheat.


> You guys been too much in school

Ah, spoken like a cheater.




-- 
Steve

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help me ? (Posting On Python-List Prohibited)

2018-02-28 Thread Aktive
On Wednesday, 28 February 2018 06:00:07 UTC+1, Lawrence D’Oliveiro  wrote:
> On Wednesday, February 28, 2018 at 4:44:04 PM UTC+13, jlad...@itu.edu wrote:
> > This is part of the reason why interviews for software developer jobs
> > have gotten so crazy.
> 
> This is why you need to have a CV that basically says “Google me”.

what the hell do you care about cheating..

the world doest care about cheating.

its about skill.

You guys been too much in school
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help me ?

2018-02-27 Thread Rick Johnson
On Tuesday, February 27, 2018 at 12:56:52 PM UTC-6, Grant Edwards wrote:
[...]
> The fun part is giving them a solution that's so obscure and "clever"
> that it technically meets the stated requirement but is so far from
> what the instructor wanted that they don't get credit for it (and
> there's no way the student will be able explain how it works to the
> instructor).

Even for the unobscure and unclever solutions (like the one
Sir Real offered), i doubt the cheaters could explain them
to any level of expertise that would be acceptable to a wise
instructor.

@OP: If after submitting your copy/paste solution the
instructor calls you over for a chat, it's okay to be
nervous, because typically this means you're about to be
outed and made a complete fool of in front of the whole
class. Yep, teachers are sadistic like that. Have a nice
day!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help me ?

2018-02-27 Thread amber


On 02/27/2018 06:54 PM, Grant Edwards wrote:
> The fun part is giving them a solution that's so obscure and "clever"
> that it technically meets the stated requirement but is so far from
> what the instructor wanted that they don't get credit for it (and
> there's no way the student will be able explain how it works to the
> instructor).

Isn't that the point of doing their homework.

Amber
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help me ?

2018-02-27 Thread jladasky
On Tuesday, February 27, 2018 at 10:56:52 AM UTC-8, Grant Edwards wrote:
> If the student is actively trying to avoid learning something, there's
> nothing you can do to help them.  They're just wasting their own time
> and money.

This is part of the reason why interviews for software developer jobs have 
gotten so crazy.  We have to weed out the impostors after they graduate.

> The fun part is giving them a solution that's so obscure and "clever"
> that it technically meets the stated requirement but is so far from
> what the instructor wanted that they don't get credit for it (and
> there's no way the student will be able explain how it works to the
> instructor).

It doesn't even need to be an obscure solution, it just needs to make use of 
things you don't expect a novice programmer to use, like lambdas.  A recent 
example:

https://groups.google.com/forum/#!original/comp.lang.python/0gYm2g3BA2A/s9xbBG1GAwAJ
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help me ?

2018-02-27 Thread Michael F. Stemper

On 2018-02-26 07:17, Stefan Ram wrote:

Percival John Hackworth  quoted:

Define 2 lists. The first one must contain the integer values 1, 2 and 3


a =[ 1, 2, 3 ]


and the second one the string values a, b and c.


b =[ 'a', 'b', 'c']


Iterate through both lists to create another list that
contains all the combinations of the A and B


for i in a:
 result = [ '1a', '1b', '1c', '2a', '2b', '2c', '3a', '3b', '3c' ]

for j in b:
 result = [ '1a', '1b', '1c', '2a', '2b', '2c', '3a', '3b', '3c' ]


That's absolutely wonderful!

However, I'd like to suggest one change, which would allow greater
CPU utilization:

for i in a:
  for j in b: # Sorry, I'm not PEP-8 compliant
result = [ '1a', '1b', '1c', '2a', '2b', '2c', '3a', '3b', '3c' ]


--
Michael F. Stemper
Always remember that you are unique. Just like everyone else.
--
https://mail.python.org/mailman/listinfo/python-list


Re: help me ?

2018-02-27 Thread Steven D'Aprano
On Tue, 27 Feb 2018 10:56:18 -0700, Ian Kelly wrote:

> Cheaters are gonna cheat. In the unlikely event they don't get the
> answer here, they'll probably just manage to convince somebody to do the
> work for them somewhere else. Honestly, I don't know if it's even worth
> the bother to engage.

Its worth the bother for the 5% who aren't *intentionally* cheating, but 
don't realise it, and just need a reminder that they need to do the work 
themselves. (Or at least give co-credit to those they got help from.) Or 
those who aren't actually doing homework, but are engaged in self-
learning.

There has to be some penalty for cheating, even if its only the minuscule 
amount of social disapproval that comes from random strangers on the 
internet telling you off, or we'll be even more overloaded by cheaters 
than we already are.



-- 
Steve

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help me ?

2018-02-27 Thread Ian Kelly
On Tue, Feb 27, 2018 at 2:50 PM, Andre Müller  wrote:
> Hello,
>
> it's a duplicate:
> https://python-forum.io/Thread-Working-with-lists-homework-2
>
> I have seen this more than one time. We don't like it. You keep people busy
> with one question at different places.

You assume that it was posted by the same person in both places, and
not by two different students in the same class.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help me ?

2018-02-27 Thread Andre Müller
Hello,

it's a duplicate:
https://python-forum.io/Thread-Working-with-lists-homework-2

I have seen this more than one time. We don't like it. You keep people busy
with one question at different places.

You need two lists and one empty list. One outer loop iterating over the
first list and one inner loop iterating over the second list. In the inner
loop you concatenate the two elements from the outer-loop and inner-loop.
Then you append them to the empty list. This text is 10 times longer as the
source code...

Complicated solution:

from string import ascii_lowercase as letter
list1 = [str(i) + c for i in range(1,4) for c in letter[:3]]
list2 = [c[::-1] for c in list1]

But this won't help you. Before you understand the code above, you have to
understand for-loops and nested for-loops. Then you can proceed with list
comprehensions. But I don't see that your intention is to learn and
understand Python. You just want to finish your homework, which bother you.

Greetings
Andre
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help me ?

2018-02-27 Thread Grant Edwards
On 2018-02-27, Ian Kelly  wrote:
> On Tue, Feb 27, 2018 at 10:16 AM, Igor Korot  wrote:
>> Congratulations!
>> You have an "A" for solving the problem and "F" for helping the guy cheat.
>> You should be expelled from the course.
>
> In my experience, this is what happens pretty much every time.
> Somebody posts a homework question asking for the answer, a few people
> say something to the effect of, "This looks like homework. What have
> you tried so far?" Then some other bozo comes along who just likes
> solving easy problems and hands up the answer on a silver platter.

If the student is actively trying to avoid learning something, there's
nothing you can do to help them.  They're just wasting their own time
and money.

The fun part is giving them a solution that's so obscure and "clever"
that it technically meets the stated requirement but is so far from
what the instructor wanted that they don't get credit for it (and
there's no way the student will be able explain how it works to the
instructor).

-- 
Grant Edwards   grant.b.edwardsYow! We just joined the
  at   civil hair patrol!
  gmail.com

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help me ?

2018-02-27 Thread Ziggy
On 2018-02-26, sotaro...@gmail.com wrote:
>
> Help me !
a=[1,2,3,]
b=["a","b","c"]
x=[]
z=[]
bonus=[]


for digits in a:
for letters in b:
x.append(str(digits) + letters)
bonus.append(letters + str(digits))
for letter in b:
for number in a:
z.append(letter + str(number))
bonus.append(str(number) + letter)
print ("1:",x)  
print ("2:",z)
print("Bonus:",bonus)


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help me ?

2018-02-27 Thread Larry Martell
On Tue, Feb 27, 2018 at 12:56 PM, Ian Kelly  wrote:
> On Tue, Feb 27, 2018 at 10:16 AM, Igor Korot  wrote:
>> Congratulations!
>> You have an "A" for solving the problem and "F" for helping the guy cheat.
>> You should be expelled from the course.
>
> In my experience, this is what happens pretty much every time.
> Somebody posts a homework question asking for the answer, a few people
> say something to the effect of, "This looks like homework. What have
> you tried so far?" Then some other bozo comes along who just likes
> solving easy problems and hands up the answer on a silver platter.
>
> Cheaters are gonna cheat. In the unlikely event they don't get the
> answer here, they'll probably just manage to convince somebody to do
> the work for them somewhere else. Honestly, I don't know if it's even
> worth the bother to engage.

When I was in college back in the 70's they made people in majors like
printing or chemistry, for example, take 1 programming course. They
were always clueless and I often wrote programs for them - my typical
fee was a case of beer.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help me ?

2018-02-27 Thread Ian Kelly
On Tue, Feb 27, 2018 at 10:16 AM, Igor Korot  wrote:
> Congratulations!
> You have an "A" for solving the problem and "F" for helping the guy cheat.
> You should be expelled from the course.

In my experience, this is what happens pretty much every time.
Somebody posts a homework question asking for the answer, a few people
say something to the effect of, "This looks like homework. What have
you tried so far?" Then some other bozo comes along who just likes
solving easy problems and hands up the answer on a silver platter.

Cheaters are gonna cheat. In the unlikely event they don't get the
answer here, they'll probably just manage to convince somebody to do
the work for them somewhere else. Honestly, I don't know if it's even
worth the bother to engage.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help me ?

2018-02-27 Thread Igor Korot
Hi,

On Tue, Feb 27, 2018 at 10:54 AM, Sir Real <nom...@adres.net> wrote:
> On Mon, 26 Feb 2018 01:40:16 -0800 (PST), sotaro...@gmail.com wrote:
>
>>Define 2 lists. The first one must contain the integer values 1, 2 and 3 and 
>>the second one the string values a, b and c. Iterate through both lists to 
>>create another list that contains all the combinations of the A and B 
>>elements. The final list should look like one of the 2 lists:
>>1. [1a, 1b, 1c, 2a, 2b, 2c, 3a, 3b, 3c]
>>2. [a1, a2. a3, b1, b2, b3, c1, c2, c3]
>>BONUS: Make the final list contain all possible combinations : [1a, a1, 1b, 
>>b1, 1c, c1, 2a, a2, 2b, b2, 2c, c2, 3a, a3, 3b, b3, 3c, c3]
>>
>>Help me !
>
> #a list of integers
> nums = [1, 2, 3]
>
> #a list of letters
> ltrs = ['a', 'b', 'c']
>
> #a list to hold the result
> rslt = []
>
> for i in nums:
> for j in ltrs:
> rslt.append(str(i) + j)
> #for bonus points uncomment the following line
> #rslt.append(j + str(i))
>
> print(rslt)
>
>
> '''RESULT
> ['1a', '1b', '1c',
>  '2a', '2b', '2c',
>  '3a', '3b', '3c']
>
>BONUS RESULT
> ['1a', 'a1', '1b', 'b1', '1c', 'c1',
>  '2a', 'a2', '2b', 'b2', '2c', 'c2',
>  '3a', 'a3', '3b', 'b3', '3c', 'c3']

Congratulations!
You have an "A" for solving the problem and "F" for helping the guy cheat.
You should be expelled from the course.

;-)

Thank you.

> '''
> --
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help me ?

2018-02-27 Thread Sir Real
On Mon, 26 Feb 2018 01:40:16 -0800 (PST), sotaro...@gmail.com wrote:

>Define 2 lists. The first one must contain the integer values 1, 2 and 3 and 
>the second one the string values a, b and c. Iterate through both lists to 
>create another list that contains all the combinations of the A and B 
>elements. The final list should look like one of the 2 lists:
>1. [1a, 1b, 1c, 2a, 2b, 2c, 3a, 3b, 3c]
>2. [a1, a2. a3, b1, b2, b3, c1, c2, c3]
>BONUS: Make the final list contain all possible combinations : [1a, a1, 1b, 
>b1, 1c, c1, 2a, a2, 2b, b2, 2c, c2, 3a, a3, 3b, b3, 3c, c3] 
>
>Help me !

#a list of integers
nums = [1, 2, 3]

#a list of letters
ltrs = ['a', 'b', 'c']

#a list to hold the result
rslt = []

for i in nums:
for j in ltrs:
rslt.append(str(i) + j)
#for bonus points uncomment the following line
#rslt.append(j + str(i))

print(rslt)


'''RESULT
['1a', '1b', '1c', 
 '2a', '2b', '2c', 
 '3a', '3b', '3c']

   BONUS RESULT
['1a', 'a1', '1b', 'b1', '1c', 'c1', 
 '2a', 'a2', '2b', 'b2', '2c', 'c2', 
 '3a', 'a3', '3b', 'b3', '3c', 'c3']
'''
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help me ?

2018-02-27 Thread alister via Python-list
On Mon, 26 Feb 2018 01:40:16 -0800, sotaro237 wrote:

> Define 2 lists. The first one must contain the integer values 1, 2 and 3
> and the second one the string values a, b and c. Iterate through both
> lists to create another list that contains all the combinations of the A
> and B elements. The final list should look like one of the 2 lists:
> 1. [1a, 1b, 1c, 2a, 2b, 2c, 3a, 3b, 3c]
> 2. [a1, a2. a3, b1, b2, b3, c1, c2, c3]
> BONUS: Make the final list contain all possible combinations : [1a, a1,
> 1b, b1, 1c, c1, 2a, a2, 2b, b2, 2c, c2, 3a, a3, 3b, b3, 3c, c3]
> 
> Help me !

Try staying awake in class where I am sure what you need would have been 
covered before the assignment was set
failing that try reading any of the python tutorials available on the 
internet




-- 
A career is great, but you can't run your fingers through its hair.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help me ?

2018-02-26 Thread ziggyvimar
On Monday, February 26, 2018 at 9:40:54 AM UTC, Negru Popi wrote:
> Define 2 lists. The first one must contain the integer values 1, 2 and 3 and 
> the second one the string values a, b and c. Iterate through both lists to 
> create another list that contains all the combinations of the A and B 
> elements. The final list should look like one of the 2 lists:
> 1. [1a, 1b, 1c, 2a, 2b, 2c, 3a, 3b, 3c]
> 2. [a1, a2. a3, b1, b2, b3, c1, c2, c3]
> BONUS: Make the final list contain all possible combinations : [1a, a1, 1b, 
> b1, 1c, c1, 2a, a2, 2b, b2, 2c, c2, 3a, a3, 3b, b3, 3c, c3] 
> 
> Help me !

Homework?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help me ?

2018-02-26 Thread Lutz Horn

Define 2 lists. ...

[...]

Help me !


Sounds like homework. Have you tried anything? Does it work?
--
https://mail.python.org/mailman/listinfo/python-list


Re: help me ?

2018-02-26 Thread Peter Otten
Christian Gollwitzer wrote:

> Am 26.02.18 um 10:40 schrieb sotaro...@gmail.com:
>> Define 2 lists. The first one must contain the integer values 1, 2 and 3
>> and the second one the string values a, b and c. Iterate through both
>> lists to create another list that contains all the combinations of the A
>> and B elements. The final list should look like one of the 2 lists: 1.
>> [1a, 1b, 1c, 2a, 2b, 2c, 3a, 3b, 3c
> 
> Look up list comprehensions.

Hm, this will teach the OP a concise way to rewrite the solution once he has 
solved the problem with the conventional nested for loops, list.append(), 
and str.format()...

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help me ?

2018-02-26 Thread Christian Gollwitzer

Am 26.02.18 um 10:40 schrieb sotaro...@gmail.com:

Define 2 lists. The first one must contain the integer values 1, 2 and 3 and 
the second one the string values a, b and c. Iterate through both lists to 
create another list that contains all the combinations of the A and B elements. 
The final list should look like one of the 2 lists:
1. [1a, 1b, 1c, 2a, 2b, 2c, 3a, 3b, 3c


Look up list comprehensions.

Christian

--
https://mail.python.org/mailman/listinfo/python-list


help me ?

2018-02-26 Thread sotaro237
Define 2 lists. The first one must contain the integer values 1, 2 and 3 and 
the second one the string values a, b and c. Iterate through both lists to 
create another list that contains all the combinations of the A and B elements. 
The final list should look like one of the 2 lists:
1. [1a, 1b, 1c, 2a, 2b, 2c, 3a, 3b, 3c]
2. [a1, a2. a3, b1, b2, b3, c1, c2, c3]
BONUS: Make the final list contain all possible combinations : [1a, a1, 1b, b1, 
1c, c1, 2a, a2, 2b, b2, 2c, c2, 3a, a3, 3b, b3, 3c, c3] 

Help me !
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: RegExp - please help me!

2017-12-27 Thread szykcech
> (?s)struct (.+?)\s*\{\s*(.+?)\s*\};

Thank you Vlastimil Brom for regexp and for explanation!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: RegExp - please help me!

2017-12-27 Thread Lele Gaifax
szykc...@gmail.com writes:

> Please help me with this regexp or tell me that I neeed do this in other way.

I think that using regexps to parse those structures is fragile and difficult
to get right[0], as there are lots of corner cases (comments, complex types,
...).

I'd suggest using a tool designed to do that, for example pycparser[1], that
provides the required infrastructure to parse C units into an AST: from there
you can easily extract interesting pieces and write out in whatever format you
need.

As an example, I used it to extract[2] enums and defines from PostgreSQL C
headers[3] and rewrite them as Python definitions[4].

Good luck,
ciao, lele.

[0] http://regex.info/blog/2006-09-15/247
[1] https://github.com/eliben/pycparser
[2] https://github.com/lelit/pg_query/blob/master/tools/extract_enums.py
[3] 
https://github.com/lfittl/libpg_query/blob/43ce2e8cdf54e4e1e8b0352e37adbd72e568e100/src/postgres/include/nodes/parsenodes.h
[4] https://github.com/lelit/pg_query/blob/master/pg_query/enums/parsenodes.py
-- 
nickname: Lele Gaifax | Quando vivrò di quello che ho pensato ieri
real: Emanuele Gaifas | comincerò ad aver paura di chi mi copia.
l...@metapensiero.it  | -- Fortunato Depero, 1929.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: RegExp - please help me! (Posting On Python-List Prohibited)

2017-12-26 Thread szykcech
W dniu wtorek, 26 grudnia 2017 21:53:14 UTC+1 użytkownik Lawrence D’Oliveiro 
napisał:
> On Wednesday, December 27, 2017 at 2:15:21 AM UTC+13, szyk...@gmail.com wrote:
> > struct (.+)\s*{\s*(.+)\s*};
> 
> You realize that “.” matches anything? Whereas I think you want to match 
> non-whitespace in those places.

I realize that. I want skip white-spaces from the beginning and from the end 
and match entire body of C++ struct declaration (with white spaces inside as 
well). Maybe should I use "".strip(" ").strip("\t").strip("\n") function after 
matching?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: RegExp - please help me!

2017-12-26 Thread Peter Pearson
On Tue, 26 Dec 2017 05:14:55 -0800 (PST), szykc...@gmail.com wrote:
[snip]
> So: I develop regexp which to my mind should work, but it doesn't and
> I don't know why. The broken regexp is like this: 
> struct (.+)\s*{\s*(.+)\s*};
[snip]

You'll probably get better help faster if you can present your problem
as a couple lines of code, and ask "Why does this print XXX, when I'm
expecting it to print YYY?"  (Sorry I'm not smart enough to give you
an answer to your actual question.)

-- 
To email me, substitute nowhere->runbox, invalid->com.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: RegExp - please help me!

2017-12-26 Thread Vlastimil Brom
Hi,
I can't comment, whether this is the right approach, as I have no
experiences with C++, but for the matching regular expression itself,
I believe, e.g. the following might work for your sample data (I am
not sure, however, what other details or variants should be taken into
account):

(?s)struct (.+?)\s*\{\s*(.+?)\s*\};

i.e. you need to escape the metacharacters { } with a backslash \
and in the current form of the pattern, you also need the flag DOTALL
- set via (?s) in the example above - in order to also match newlines
with . (alternatively, you could use \n specifically in the pattern,
where needed.) it is possible, that an online regex tester uses some
flags implicitly.

I believe, the non-greedy quantifiers are suitable here  +?
matching as little as possible, otherwise the pattern would match
between the first and the last structs in the source text at once.

It seems, the multiline flag is not needed here, as there are no
affected metacharacters.

hth,
   vbr

=

2017-12-26 14:14 GMT+01:00, szykc...@gmail.com <szykc...@gmail.com>:
> Hi
> I use online Python reg exp editor https://pythex.org/ and I use option
> "multiline".
> I want to use my reg exp in Python script to generate automatically some
> part of my program written in C++ (database structure and serialization
> functions). In order to do this I need: 1) C++ struct name and 2) struct
> definition. Struct definition I need because some inline functions can
> appear bellow my struct definition and makes inappropriate further regexp
> filtering (against variables).
>
> So: I develop regexp which to my mind should work, but it doesn't and I
> don't know why. The broken regexp is like this:
> struct (.+)\s*{\s*(.+)\s*};
> As you can see it has two groups: struct name and struct definition.
> It fails even for such simple structure:
> struct Structure
> {
> int mVariable1;
> QString mVariable2;
> bool mVariable3
> };
>
> Please help me with this regexp or tell me that I neeed do this in other
> way.
>
> thanks, happy Christmas, and happy New Year
> Szyk Cech
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


RegExp - please help me!

2017-12-26 Thread szykcech
Hi
I use online Python reg exp editor https://pythex.org/ and I use option 
"multiline".
I want to use my reg exp in Python script to generate automatically some part 
of my program written in C++ (database structure and serialization functions). 
In order to do this I need: 1) C++ struct name and 2) struct definition. Struct 
definition I need because some inline functions can appear bellow my struct 
definition and makes inappropriate further regexp filtering (against variables).

So: I develop regexp which to my mind should work, but it doesn't and I don't 
know why. The broken regexp is like this:
struct (.+)\s*{\s*(.+)\s*};
As you can see it has two groups: struct name and struct definition.
It fails even for such simple structure:
struct Structure
{
int mVariable1;
QString mVariable2;
bool mVariable3
};

Please help me with this regexp or tell me that I neeed do this in other way.

thanks, happy Christmas, and happy New Year
Szyk Cech
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can anybody help me retrieve how to retrieve output from this Python code below!

2017-07-11 Thread Peter Otten
ksatish@gmail.com wrote:

[snip code]

Wasn't there any documentation to go with that script? That's the preferable 
method to use software written by someone else ;)


Anyway -- First you have to undo what was probably changed by yourself:

$ diff -u json2csv_orig.py json2csv.py
--- json2csv_orig.py2017-07-11 15:15:06.527571509 +0200
+++ json2csv.py 2017-07-11 15:14:17.878514787 +0200
@@ -132,14 +132,6 @@
 
 return parser
 
-json_file = input("Type Json input file name: ")
-
-key_map = input("Type Key value : ")
-
-MultiLineJson2Csv(Json2Csv).init_parser()
-
-Json2Csv.load(json_file)
-
 
 if __name__ == '__main__':
 parser = init_parser()
@@ -159,4 +151,4 @@
 fileName, fileExtension = os.path.splitext(args.json_file.name)
 outfile = fileName + '.csv'
 
-loader.write_csv(filename=outfile, make_strings=args.strings)
+loader.write_csv(filename=outfile, make_strings=args.strings)

Then you have to create a file containing the data in json format, e. g.

$ cat data.json
[
["alpha", "beta", {"one": {"two": "gamma"}}],
["zeta", "eta", {"one": {"two": "theta"}}]
]

...and a file describing the conversion, also in json, like

$ cat key_map.json
{
   "map": [
   ["foo", "0"],
   ["bar", "1"],
   ["baz", "2.one.two"]
   ]
}

Now you can run the script, first to look at the command line help

$ python json2csv.py -h
usage: json2csv.py [-h] [-e] [-o OUTPUT_CSV] [--strings] json_file key_map

Converts JSON to CSV

positional arguments:
  json_file Path to JSON data file to load
  key_map   File containing JSON key-mapping file to load

optional arguments:
  -h, --helpshow this help message and exit
  -e, --each-line   Process each line of JSON file separately
  -o OUTPUT_CSV, --output-csv OUTPUT_CSV
Path to csv file to output
  --strings Convert lists, sets, and dictionaries fully to 
comma-separated strings.

and then to process your data:

$ python json2csv.py data.json key_map.json
INFO:root:[u'alpha', u'beta', {u'one': {u'two': u'gamma'}}]
INFO:root:[u'zeta', u'eta', {u'one': {u'two': u'theta'}}]

Finally, let's have a look at the resulting csv file:

$ cat data.csv
foo,bar,baz
alpha,beta,gamma
zeta,eta,theta


-- 
https://mail.python.org/mailman/listinfo/python-list


Can anybody help me retrieve how to retrieve output from this Python code below!

2017-07-11 Thread ksatish . dtc
try:
import unicodecsv as csv
except ImportError:
import csv

import json
import operator
import os
from collections import OrderedDict
import logging

logging.basicConfig(level=logging.DEBUG)

class Json2Csv(object):
"""Process a JSON object to a CSV file"""
collection = None

# Better for single-nested dictionaries
SEP_CHAR = ', '
KEY_VAL_CHAR = ': '
DICT_SEP_CHAR = '\r'
DICT_OPEN = ''
DICT_CLOSE = ''

# Better for deep-nested dictionaries
# SEP_CHAR = ', '
# KEY_VAL_CHAR = ': '
# DICT_SEP_CHAR = '; '
# DICT_OPEN = '{ '
# DICT_CLOSE = '} '

def __init__(self, outline):
self.rows = []

if not isinstance(outline, dict):
raise ValueError('You must pass in an outline for JSON2CSV to 
follow')
elif 'map' not in outline or len(outline['map']) < 1:
raise ValueError('You must specify at least one value for "map"')

key_map = OrderedDict()
for header, key in outline['map']:
splits = key.split('.')
splits = [int(s) if s.isdigit() else s for s in splits]
key_map[header] = splits

self.key_map = key_map
if 'collection' in outline:
self.collection = outline['collection']

def load(self, json_file):
self.process_each(json.load(json_file))

def process_each(self, data):
"""Process each item of a json-loaded dict
"""
if self.collection and self.collection in data:
data = data[self.collection]

for d in data:
logging.info(d)
self.rows.append(self.process_row(d))

def process_row(self, item):
"""Process a row of json data against the key map
"""
row = {}

for header, keys in self.key_map.items():
try:
row[header] = reduce(operator.getitem, keys, item)
except (KeyError, IndexError, TypeError):
row[header] = None

return row

def make_strings(self):
str_rows = []
for row in self.rows:
str_rows.append({k: self.make_string(val)
 for k, val in row.items()})
return str_rows

def make_string(self, item):
if isinstance(item, list) or isinstance(item, set) or isinstance(item, 
tuple):
return self.SEP_CHAR.join([self.make_string(subitem) for subitem in 
item])
elif isinstance(item, dict):
return self.DICT_OPEN + 
self.DICT_SEP_CHAR.join([self.KEY_VAL_CHAR.join([k, self.make_string(val)]) for 
k, val in item.items()]) + self.DICT_CLOSE
else:
return unicode(item)

def write_csv(self, filename='output.csv', make_strings=False):
"""Write the processed rows to the given filename
"""
if (len(self.rows) <= 0):
raise AttributeError('No rows were loaded')
if make_strings:
out = self.make_strings()
else:
out = self.rows
with open(filename, 'wb+') as f:
writer = csv.DictWriter(f, self.key_map.keys())
writer.writeheader()
writer.writerows(out)


class MultiLineJson2Csv(Json2Csv):
def load(self, json_file):
self.process_each(json_file)

def process_each(self, data, collection=None):
"""Load each line of an iterable collection (ie. file)"""
for line in data:
d = json.loads(line)
if self.collection in d:
d = d[self.collection]
self.rows.append(self.process_row(d))


def init_parser():
import argparse
parser = argparse.ArgumentParser(description="Converts JSON to CSV")
parser.add_argument('json_file', type=argparse.FileType('r'),
help="Path to JSON data file to load")
parser.add_argument('key_map', type=argparse.FileType('r'),
help="File containing JSON key-mapping file to load")
parser.add_argument('-e', '--each-line', action="store_true", default=False,
help="Process each line of JSON file separately")
parser.add_argument('-o', '--output-csv', type=str, default=None,
help="Path to csv file to output")
parser.add_argument(
'--strings', help="Convert lists, sets, and dictionaries fully to 
comma-separated strings.", action="store_true", default=True)

return parser

json_file = input("Type Json input file name: ")

key_map = input("Type Key value : ")

MultiLineJson2Csv(Json2Csv).init_parser()

Json2Csv.load(json_file)


if __name__ == '__main__':
parser = init_parser()
args = parser.parse_args()

key_map = json.load(args.key_map)
loader = None
if args.each_line:
loader = MultiLineJson2Csv(key_map)
else:
loader = Json2Csv(key_map)

loader.load(args.json_file)

outfile = args.output_csv
if outfile is None:
fileName, fileExtension = 

Re: Help me cythonize a python routine!

2016-11-10 Thread BartC

On 09/11/2016 21:25, breamore...@gmail.com wrote:

On Wednesday, November 9, 2016 at 7:34:41 PM UTC, BartC wrote:



However according to your mindset nothing matters provided it's fast,

> accuracy does not matter to users.


Hence your recent comment on another thread about converting invalid integer 
entries into zero.


That's by design. And it's not unprecedented; using C's 'atoi()' 
function (convert a string to an integer), then inputs of "" and "ABC" 
both return 0. Input of "123ABC" returns 123.


And in the context that was being discussed, it was desired that hitting 
end-of-line while attempting to read more items should return null 
values such as 0, 0.0 or "".


For any more refined behaviour, values can be read differently (read as 
strings then converted with routines that do more validation).


Effectively, the conversion looks at the entire line buffer contents 
remaining, and converts the first integer encountered, if any, then 
removes that and any terminator from the buffer.


If I try something like that in Python, trying to convert an integer at 
the beginning of a string, it fails: int("123,456"), int("123 456"),
int("63924 the"). It will need processing first so that the parameter 
comprises only the thing we're trying to read.


Anyway the comparison between Python and that particular /lower-level/ 
language is moot as Python apparently doesn't have a way of directly 
reading items from an input line, either from a console or from a file.


You have to read a line as one string then apply DIY conversions. Which 
the other language could equally do.


So it's a detail. The other language could also have chosen to use 
exceptions to signal such events (no integer following, end of input, 
invalid terminator etc). I chose to keep it simple and to make it work 
the same way it's always done.


--
Bartc
--
https://mail.python.org/mailman/listinfo/python-list


Re: Help me cythonize a python routine!

2016-11-09 Thread Steven D'Aprano
On Thursday 10 November 2016 18:23, Andrea D'Amore wrote:

> On 10 November 2016 at 00:15, Steve D'Aprano 
> wrote:
>> py> import collections
> […]
>> py> import os
>> py> os.listdir('/usr/local/lib/python3.5/collections/')
> 
> Not
> 
> os.listdir(collections.__path__[0])
> 
> since it's already there?


I was working in the interactive interpreter, and it was easier and more 
convenient to copy the path from a previous line's output, than to type a new 
expression.



-- 
Steven
299792.458 km/s — not just a good idea, it’s the law!

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help me cythonize a python routine!

2016-11-09 Thread Andrea D'Amore
On 10 November 2016 at 00:15, Steve D'Aprano  wrote:
> py> import collections
[…]
> py> import os
> py> os.listdir('/usr/local/lib/python3.5/collections/')

Not

os.listdir(collections.__path__[0])

since it's already there?



-- 
Andrea
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help me cythonize a python routine!

2016-11-09 Thread Ethan Furman

On 11/09/2016 04:30 PM, Michael Torrie wrote:

On 11/09/2016 04:21 PM, Ethan Furman wrote:

On 09/11/2016 21:25, breamore...@gmail.com wrote:


[...filtered...]

Mark, you do not need to be insulting nor condescending.


Agreed.  Is he still being filtered on the mailing list?  He's still in
my killfile.


Yes.

--
~Ethan~
--
https://mail.python.org/mailman/listinfo/python-list


Re: Help me cythonize a python routine!

2016-11-09 Thread Michael Torrie
On 11/09/2016 04:21 PM, Ethan Furman wrote:
>> On 09/11/2016 21:25, breamore...@gmail.com wrote:
> 
> [...filtered...]
> 
> Mark, you do not need to be insulting nor condescending.

Agreed.  Is he still being filtered on the mailing list?  He's still in
my killfile.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help me cythonize a python routine!

2016-11-09 Thread Ethan Furman

On 09/11/2016 21:25, breamore...@gmail.com wrote:


[...filtered...]

Mark, you do not need to be insulting nor condescending.

--
~Ethan~
--
https://mail.python.org/mailman/listinfo/python-list


Re: Help me cythonize a python routine!

2016-11-09 Thread Steve D'Aprano
On Thu, 10 Nov 2016 10:01 am, BartC wrote:

> I haven't ruled out that collections is written in Python. But I can't
> find a 'collections.py' module in my Python 3.4; the nearest is
> "__init__.py". And there /is/ a lot of code there.

And that's exactly right.

py> import collections
py> collections.__file__
'/usr/local/lib/python3.5/collections/__init__.py'

That's because collections is a package, not just a single file module:

py> collections.__package__
'collections'


Which means it is made up of a single directory "collections", a file
collections/__init__.py which makes it a package, plus any additional
sub-modules or sub-packages under the collections directory:

py> import os
py> os.listdir('/usr/local/lib/python3.5/collections/')
['__init__.py', '__pycache__', '__main__.py', 'abc.py']


You can ignore the __pycache__ directory, that's just used for caching the
byte-code compiled .pyc files. __main__.py is used if you try to run
collections as a script:

python3.5 -m collections  # will run collections/__main__.py

and the submodule abc.py is automatically imported for you:


py> collections.abc






-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help me cythonize a python routine!

2016-11-09 Thread BartC

On 09/11/2016 21:25, breamore...@gmail.com wrote:

On Wednesday, November 9, 2016 at 7:34:41 PM UTC, BartC wrote:



All the real work is done inside the Collections module. If that was
written in Python, then you'd have to Cythonise that, and there might be
quite a lot of it!

But I think 'collections' is a built-in module which means it's already
in something like C. So it might already be as fast as it gets (0.7 to
0.8 seconds on my machine), unless perhaps a different algorithm is used.


'collections' isn't a built-in module, it's part of the stdlib, again showing 
your complete ignorance of the entire Python setup.  However according to your 
mindset nothing matters provided it's fast, accuracy does not matter to users.  
Hence your recent comment on another thread about converting invalid integer 
entries into zero.  I weep every time I think about it, which is quite often.


I haven't ruled out that collections is written in Python. But I can't 
find a 'collections.py' module in my Python 3.4; the nearest is 
"__init__.py". And there /is/ a lot of code there.



To the OP: there was a long thread in comp.lang.c about tasks like this 
in a variety of languages:


https://groups.google.com/forum/#!topic/comp.lang.c/n2gvRytNblI%5B326-350%5D

The first solution that corresponds exactly to your task (In Python but 
with a different method) is at the bottom of page 14; 19-Dec-15.


I posted part of a version in compiled code that runs in about 70msec 
(the fastest PyPy was 600msec). So some speed-up /is/ possible with the 
right approach. The method I used was something like this:


 - Read the entire file into memory (eg. as string or byte-array)

 - Initialise a hashtable D (ie. dict) to empty, where each entry
   is a word, and a count

 - Scan that memory data recognising words

 - For each word, look it up in D. Increment its count if found;
   add it with a count of 1 if not

 - At the end, rather than sort, just scan D 20 times looking for
   the word with the nth highest count (n is 1 to 20), and display.

This can be written in pure Python for the algorithm part, without 
needing to use 'collections', only dicts. That could offer an easier 
opportunity to apply Cython tweaks.


--
Bartc


--
https://mail.python.org/mailman/listinfo/python-list


Re: Help me cythonize a python routine!

2016-11-09 Thread BartC

On 05/11/2016 04:11, DFS wrote:


It reads in a text file of the Bible, and counts the Top 20 most common
words.

http://www.truth.info/download/bible.htm


import time; start=time.clock()
import sys, string
from collections import Counter

#read file
with open(sys.argv[1],'r') as f:
chars=f.read().lower()

#remove numbers and punctuation
chars=chars.translate(None,string.digits)
chars=chars.translate(None,string.punctuation)

#count words
counts=Counter(chars.split()).most_common(20)   

#print
i=1
for word,count in counts:
print str(i)+'.',count,word
i+=1

print "%.3gs"%(time.clock()-start)





1.17s isn't too bad, but it could be faster.



Is it easy to cythonize?  Can someone show me how?

I installed Cython and made some attempts but got lost.


The trouble there isn't really any Python code here to Cythonise.

All the real work is done inside the Collections module. If that was 
written in Python, then you'd have to Cythonise that, and there might be 
quite a lot of it!


But I think 'collections' is a built-in module which means it's already 
in something like C. So it might already be as fast as it gets (0.7 to 
0.8 seconds on my machine), unless perhaps a different algorithm is used.


--
Bartc


--
https://mail.python.org/mailman/listinfo/python-list


Re: Help me!, I would like to find split where the split sums are close to each other?

2016-10-16 Thread Michael Torrie
On 10/16/2016 05:25 AM, k.adema...@gmail.com wrote:
> Help me!, I would like to find split where the split sums are close
> to each other?
> 
> I have a list is
> 
> test = [10,20,30,40,50,60,70,80,90,100]
> 
> ​and I would like to find split where the split sums are close to
> each other by number of splits = 3 that ​all possible combinations
> and select the split where the sum differences are smallest.
> 
> Please example code or simple code Python.

Ahh, sounds like a homework problem, which we will not answer directly,
if at all.

If you had no computer at all, how would you do this by hand?  Can you
describe the process that would identify how to split the piles of
candies, money, or whatever other representation you might use?  So
forgetting about Python and the specifics of making a valid program, how
would you solve this problem?  What steps would you take? This is known
as an algorithm.  Once you have that figured out, then you can begin to
express the algorithm as a computer program.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help me!, I would like to find split where the split sums are close to each other?

2016-10-16 Thread breamoreboy
On Sunday, October 16, 2016 at 12:27:00 PM UTC+1, k.ade...@gmail.com wrote:
> Help me!, I would like to find split where the split sums are close to each 
> other?
> 
> I have a list is
> 
> test = [10,20,30,40,50,60,70,80,90,100]
> 
> ​and I would like to find split where the split sums are close to each other 
> by number of splits = 3 that ​all possible combinations and select the split 
> where the sum differences are smallest.
> 
> Please example code or simple code Python.
> 
> Thank you very much
> 
> K.ademarus

We do not write code for you.  I'd suggest you start here 
https://docs.python.org/3/library/itertools.html

Kindest regards.

Mark Lawrence.
-- 
https://mail.python.org/mailman/listinfo/python-list


Help me!, I would like to find split where the split sums are close to each other?

2016-10-16 Thread k . ademarus
Help me!, I would like to find split where the split sums are close to each 
other?

I have a list is

test = [10,20,30,40,50,60,70,80,90,100]

​and I would like to find split where the split sums are close to each other by 
number of splits = 3 that ​all possible combinations and select the split where 
the sum differences are smallest.

Please example code or simple code Python.

Thank you very much

K.ademarus
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help me

2016-03-30 Thread Ethan Furman

On 03/30/2016 06:10 AM, srinivas devaki wrote:


ahh, this is the beginning of a conspiracy to waste my time.

PS: just for laughs. not to offend any one.


It's fair:  you waste ours, we waste yours.  :)  A fair, if not good, trade.

--
~Ethan~

--
https://mail.python.org/mailman/listinfo/python-list


Re: Help me

2016-03-30 Thread srinivas devaki
ahh, this is the beginning of a conspiracy to waste my time.

PS: just for laughs. not to offend any one.

Regards
Srinivas Devaki
Junior (3rd yr) student at Indian School of Mines,(IIT Dhanbad)
Computer Science and Engineering Department
ph: +91 9491 383 249
telegram_id: @eightnoteight
On Mar 30, 2016 2:11 PM, "Ben Finney"  wrote:

> Smith  writes:
>
> > Il 29/03/2016 11:17, Ben Finney ha scritto:
> > > You'll get better help if you:
> > >
> > > * Summarise the problem briefly in the Subject field.
> > >
> > > * Actually say anything useful in the message body.
> > >
> > thanks a lot
>
> You're welcome. Feel free to ask about the Python language here,
> following the advice above.
>
> --
>  \  “Programs must be written for people to read, and only |
>   `\incidentally for machines to execute.” —Abelson & Sussman, |
> _o__)  _Structure and Interpretation of Computer Programs_ |
> Ben Finney
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help me

2016-03-30 Thread Ben Finney
Smith  writes:

> Il 29/03/2016 11:17, Ben Finney ha scritto:
> > You'll get better help if you:
> >
> > * Summarise the problem briefly in the Subject field.
> >
> > * Actually say anything useful in the message body.
> >
> thanks a lot

You're welcome. Feel free to ask about the Python language here,
following the advice above.

-- 
 \  “Programs must be written for people to read, and only |
  `\incidentally for machines to execute.” —Abelson & Sussman, |
_o__)  _Structure and Interpretation of Computer Programs_ |
Ben Finney

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help me

2016-03-30 Thread Smith

Il 29/03/2016 11:17, Ben Finney ha scritto:

Smith  writes:


[a URL]


You'll get better help if you:

* Summarise the problem briefly in the Subject field.

* Actually say anything useful in the message body.


thanks a lot
--
https://mail.python.org/mailman/listinfo/python-list


Re: Help me

2016-03-29 Thread Ben Finney
Smith  writes:

> [a URL]

You'll get better help if you:

* Summarise the problem briefly in the Subject field.

* Actually say anything useful in the message body.

-- 
 \ “My house is on the median strip of a highway. You don't really |
  `\notice, except I have to leave the driveway doing 60 MPH.” |
_o__)   —Steven Wright |
Ben Finney

-- 
https://mail.python.org/mailman/listinfo/python-list


Help me

2016-03-29 Thread Smith

https://github.com/githubdavide/ip-pubblico-send/blob/master/ip-pubblico.py
--
https://mail.python.org/mailman/listinfo/python-list


Re: TSP in python ; this is code to solve tsp whenever called, where given coordinates as in name of pos and then start coordinate as in start, help me how it works ?

2016-03-20 Thread Mark Lawrence

On 18/03/2016 17:04, Qurrat ul Ainy wrote:

help required !!!



For what, house cleaning?

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

--
https://mail.python.org/mailman/listinfo/python-list


Re: TSP in python ; this is code to solve tsp whenever called, where given coordinates as in name of pos and then start coordinate as in start, help me how it works ?

2016-03-20 Thread Qurrat ul Ainy
help required !!!
-- 
https://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   6   7   8   >