r/learningpython • • Sep 04 '21

A question: which is better, stylistically ("Pythonicness"?) or otherwise.

2 Upvotes

I have a list of sorted lists. I want to grab an element of each in turn and print it out until I've printed them all. The lists are of different length.

At first I rolled my own:

lol_files = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i', 'j', 'k']]

while any(lol_files):
    for l in lol_files:
        if l:
            print(l.pop(0))

And that works, and looks clean to my eye (albeit a bit "arrowhead-y"). But then I ran across zip_longest in itertools and thought this must yield a bettter, 'more pythonic' way.

But there kept on being gotchas, so the briefest I could make it was:

 lol_files = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i', 'j', 'k']]

 from itertools import zip_longest, chain

 for f in [x for x in chain(*zip_longest(*lol_files)) if x ]:
    print(f)

which could also have been:

print('\n'.join([x for x in chain(*zip_longest(*lol_files)) if x ]))

The *lol_files is coz zip_longest doesn't do the right thing with the structure a list of lists - it wants the literal, comma-separated, manual entry of a list of lists. The * fixes that.

Ditto for chain(*zip_longest(... although the chain.from_iterable form is available, but I was fighting for brevity at this point, which is also why the specific imports.

And then I had to wrap that in [ x for x in .... if x] because zip_longest insists on putting something in place of the elements not filled by the shorter lists, and what ever it is I don't want to print that, as it won't be a proper filename. (I could have used filter(lambda x: x, ...) but I'm pretty sure the list comprehension version is considered 'more pythonic'. Plus the shit starts looking like Lisp, lol.

The longer form is:

 import itertools
 for f in [x for x in itertools.chain.from_iterable(itertools.zip_longest(*lol_files)) if x]:
    print(f)

r/learningpython • • Sep 01 '21

What does name_var.set(" ") and passw_var.set(" ") do in this code? Currently self teaching tkinter.

2 Upvotes

Hello,

I have taken the code below from the geeksforgeeks website. I am using their tkinter tutorial to teach myself how to make GUIs via python.

I am having trouble understanding the code. I do not understand what is the purpose of name_var.set(" ") and passw_var.set(" ").

I removed those two lines of code from the submit function, and was able to get the same result.

Could someone explain to me the significance of those two lines of code?

geeksforgeeks link: https://www.geeksforgeeks.org/python-tkinter-entry-widget/

# Program to make a simple
# login screen


import tkinter as tk

root=tk.Tk()

# setting the windows size
root.geometry("600x400")

# declaring string variable
# for storing name and password
name_var=tk.StringVar()
passw_var=tk.StringVar()


# defining a function that will
# get the name and password and
# print them on the screen
def submit():

	name=name_var.get()
	password=passw_var.get()
	
	print("The name is : " + name)
	print("The password is : " + password)
	
	name_var.set("")
	passw_var.set("")
	
	
# creating a label for
# name using widget Label
name_label = tk.Label(root, text = 'Username', font=('calibre',10, 'bold'))

# creating a entry for input
# name using widget Entry
name_entry = tk.Entry(root,textvariable = name_var, font=('calibre',10,'normal'))

# creating a label for password
passw_label = tk.Label(root, text = 'Password', font = ('calibre',10,'bold'))

# creating a entry for password
passw_entry=tk.Entry(root, textvariable = passw_var, font = ('calibre',10,'normal'), show = '*')

# creating a button using the widget
# Button that will call the submit function
sub_btn=tk.Button(root,text = 'Submit', command = submit)

# placing the label and entry in
# the required position using grid
# method
name_label.grid(row=0,column=0)
name_entry.grid(row=0,column=1)
passw_label.grid(row=1,column=0)
passw_entry.grid(row=1,column=1)
sub_btn.grid(row=2,column=1)

# performing an infinite loop
# for the window to display
root.mainloop()

r/learningpython • • Aug 30 '21

Run an app in specific date and time (In the specific date)

2 Upvotes

Hi all .

I have the following code . I would like to schedule it to run in specific dates ,at the same hour . I tried to do it with schedule module but it seems schedule doesn't have the option for specific dates . Is it something I can achieve with Time module or maybe other module that provides this ?

At the end I would like to convert it to exe and make it run in those specific dates by hard code it in the code itself .

Thx .

from win10toast import ToastNotifier
import time
import schedule

    #Notification that Runs every X time
    def notificationsettings():
        pass
    notification = ToastNotifier()
    notification.show_toast(title=  "A game is scheduled for today. 
        Consider to leave early",
    icon_path = "C:\Tools\FGMT\FGMT.ico", duration = 10)

    schedule.every().monday.at("10:30").do(notificationsettings)

r/learningpython • • Aug 28 '21

How To Find And Correct Data Correlation To Avoid The Pain Later | Data Preprocessing In Python EP 3

Thumbnail
youtube.com
2 Upvotes

r/learningpython • • Aug 23 '21

Microservices and datasource

2 Upvotes

Hi,

I'm trying to understand a coding test for a job interview, I was expecting a junior role, but the coding test is for a senior role, I can't at this moment work out if they just want to see how far I get, whatever the outcome, the topic is on microservices and I want to learn about them, there is plenty of resources and I have a basic understanding. The test is to build a microservice that is production ready, my question is this: they have not given me a data source, and as a result I'm am suspecting that a microservice should be agnostic to the data source to some extent, I know roughly where this datasource is likely coming from as we have to interrogate it in my current role, however, this role is open to the public so the assumption is that the datasource is unknown. Is this correct thinking, or for job interview tests like these, are employers looking at how you would creatively mock up a data source or is it just that, it is expected that I should know how to make a component that can simply plug in.

This microservice is purely poling a database for items in a date range and returning a list, I have done this with Flask and I have just mocked up a csv file for the data, and then of course unittests I suspect is what they are actually looking to see as production ready to me means more a case of "do you understand what it means to be production ready", so testing is a given.

for clarity, this is a role for a python developer specifically.


r/learningpython • • Aug 21 '21

Episode 2 Every Astounding Machine Learning Model Starts With Data Visualization

Thumbnail
youtube.com
2 Upvotes

r/learningpython • • Aug 03 '21

Installing And Using Kaggle's Python API

Thumbnail
youtu.be
2 Upvotes

r/learningpython • • Jul 19 '21

Can We Evolve Our Queue Into A Priority Queue ???|Stock Analysis Tool

Thumbnail
youtu.be
2 Upvotes

r/learningpython • • Jun 29 '21

Visualization help

2 Upvotes

I apologize if this sounds vague but what are some good ways to visualize NLP data that is not focused on words?

In my case, I used doc2vec and am now comparing the documents using gensim. I don't want to focus on words but the overall similarity between texts.

Note: I also posted the on r/LanguageTechnology


r/learningpython • • Jun 22 '21

Learning pyautogui

2 Upvotes

This is a silly, simple issue, but I'm having trouble figuring out how to get multiple functions to actually execute using keyboard strokes in pyautogui. The following code is intended to alt-tab-tab-tab 3 times in order to shuffle around which windows have focus, but when I run it, it only executes the first series of maneuvers. I'm recreating what I would be doing with my fingers, not sure why it doesn't work.

pyautogui.keyDown('alt'); pyautogui.press('tab'); pyautogui.press('tab'); pyautogui.press('tab'); pyautogui.keyUp('alt')
pyautogui.keyDown('alt'); pyautogui.press('tab'); pyautogui.press('tab'); pyautogui.press('tab'); pyautogui.keyUp('alt')
pyautogui.keyDown('alt'); pyautogui.press('tab'); pyautogui.press('tab'); pyautogui.press('tab'); pyautogui.keyUp('alt')

to be clear, if I'm starting with my window focus as A-B-C-D, I'm expecting this to shuffle them to look like B-C-D-A, instead it stops at D-A-B-C


r/learningpython • • Jun 18 '21

Learning python for beginners

Thumbnail self.python
2 Upvotes

r/learningpython • • Jun 10 '21

Python Merge Sort | Youtube Keyword Planner

Thumbnail
youtu.be
2 Upvotes

r/learningpython • • May 28 '21

Word Dictionary using Tkinter

2 Upvotes

Hi Folks,

Hope you are doing great today!

I am sharing with you "How to create a Word Dictionary using Tkinter in Python".

https://techarge.in/word-dictionary-using-tkinter/

#python #programming #pythonprojects #coding


r/learningpython • • May 11 '21

How to get python to work fast with facebook's cinder.

Thumbnail
youtube.com
2 Upvotes

r/learningpython • • Apr 30 '21

zip files with .py

2 Upvotes

need help. My professor in my Intro to Programming Python class provided a zip file with .py files to do peer reviews. I can download the file , but can't access the file. Do I need python on my laptop to view the files?


r/learningpython • • Apr 27 '21

Guidance on Searching, finding latest file, converting from pdf to jpg, save all in same folder.

2 Upvotes

I am just learning python but I'm trying to automate a tedious task that's folded into a larger process.

My office has multi sheet pdf files saved in the same named folder across many (75+) project folders. I would like python to go to the specific named folder in each of the 75+ project folders, find the latest file, convert the entire file to a jpg, then save them all in one specific folder. All files are on Box.

I understand I need poppler and PDF2image but I'm lost about finding the same folder name in many different parent folders as well as only converting the latest saved file.

Any help would be much appreciate.


r/learningpython • • Apr 03 '21

I'm not in/out of my loops properly

2 Upvotes

Hi all. I believe the problem i am having with my code is that i'm not fully grasping when i am in my own loop that i have created or not... or something. I'm just missing something about loops. Can someone please look at how i went wrong here and help me think the right way? I'm nervous about formatting etc here on reddit. I'm taking an intro class, not too tech savvy.

My problem asked to: Write a function shampoo_instructions() with parameter num_cycles. If num_cycles is less than 1, print "Too few.". If more than 4, print "Too many.". Else, print "N : Lather and rinse." num_cycles times, where N is the cycle number, followed by "Done.".

I wrote:

def shampoo_instructions(num_cycles):

num_cycles = user_cycles

N = num_cycles

if num_cycles < 1:

print("Too few.")

elif num_cycles > 4:

print("Too many.")

elif N > 0:

print(N, " : Lather and rinse.")

N - 1

print("Done.")

user_cycles = int(input())

shampoo_instructions(user_cycles)

My output is close:

2 : Lather and rinse.

Done.

They wanted:

1 : Lather and rinse.

2 : Lather and rinse.

Done.

Anyone have any advice? I'll also take advice on how to format questions with code in here better.


r/learningpython • • Mar 03 '21

Can I just add a library to an existing environment with "Pipenv install (insert name of additional library)"? or is it done differently?

2 Upvotes

I just want to make sure that this is the right way to do this.

I have a folder where I did "pipenv install pandas".

Turns out I also need matplotlib, so do I just do "pipenv install matplotlib"?

Or will that start a completely new pipfile? Or a new environment ?


r/learningpython • • Feb 23 '21

Is there a way to know which libraries I got already installed with Python?

2 Upvotes

I'm using Linux Mint 20 (Ubuntu 20.04)
Python 3.8.5 (Without Conda)


r/learningpython • • Feb 22 '21

Combining lower() and strip()

2 Upvotes

how do I combine lower() and strip() when using if/else statement?


r/learningpython • • Feb 16 '21

How can I get my discord bot to read me dms

2 Upvotes

So I want to make my discord bot read me dms it gets sent but it wont work. this is the code Im using

It wont let me say @ but the u/ is @

u/client.event
async def on_message(message):
    ledipbot_channel=client.get_channel(793586177328283660)
    channel = client.get_channel(713181767330299957)
if message.guild is None and message.author != client.user:
await ledipbot_channel.send(channel, message.content)
await client.process_commands(message)

It says that it accepts 1-2 positional arguments but was given 3. Idk what that means can you guys help?


r/learningpython • • Feb 15 '21

ValueError

2 Upvotes
Hi there, this is my code:


import csv
import pandas
import random
with open('data.txt', errors = "ignore") as csv_file, open("output.txt", "w") as out_file:
    csv_reader = csv_file.readlines()
    for row in csv_reader:
        original_rows = 10019
        desired_rows = 500
        skip = sorted(random.sample(range(original_rows), original_rows-desired_rows))
        df = pandas.read_csv(csv_reader, skiprows=skip)


when running it I get an erro message ---->  ValueError: Invalid file path or buffer object type: <class 'list'> 

How can I improve the code? My task is to randomly choose n number of raws from a csv file

Besides, I need to add the randomly chosen raws to another csv file. Would be great if anyone could help :)


r/learningpython • • Feb 11 '21

What is the difference between these two expressions

2 Upvotes

What is the difference???

Assume there is a text file called rdnum.txt

in the file:

3.485749
  788737   
  364777 
file = 'rdnnum.txt'

the first expression:

with open(file) as fo:     
    for i in range(4):         
        print(fo.read()) 

the second expression:

with open(file) as fo:     
    num = file.read() 
for i in range(4):     
    print(num) 

Why the results are different from these two expressions???


r/learningpython • • Jan 29 '21

I need help learning the object orinted appraoch

2 Upvotes

Hello guys I am new to programming and i have been learning python i took a course and i was good until we reached the object oriented part i didn't understand a word from my instructor any reccomendations on where to find a good explanation for this ?


r/learningpython • • Jan 25 '21

Global modules?

2 Upvotes

Hi, Is there a way to create a module that than can be accessed and imported from everywhere, similar to modules installed over pip?