Creating shapes with while loop Python - python-3.x

What I am trying to do is use a while loop to create a square out of asterixs, the code below will print the square filled in, but what I want it to do is print the square unfilled
a='square'
b='unfilled'
c=4
num=0
asterix='*'
while a=='square' and b=='unfilled' and int(num)<int(c):
num+=1
print(asterix*int(c))
What the code does:
****
****
****
****
What I want the code to do:
****
* *
* *
****
Any help would be much appreciated

n = 4
s = "*"
for i in range(0,n,1):
if i == 0 or i == n-1:
print(s*n)
else:
print(s+(" "*(n-2))+s)
This should do what you want to. You don't have to convert everything correct.

I know this was answered a long time ago, but I am going through some of my earlier class exercises too and trying to use some of the new things I have learned along the way.
This reminds me a lot of one of my exercises and I eventually answered it similar to the answer above. Since then I have discovered a nice way to write this using a generator:
n = 4
table = ("* *" if i not in [0, n] else '****' for i in range(n+1))
for row in table: print(row)
You would probably want to generalise this too so that it worked for a variable size, n.

Related

Shortest path trough a set of points

I have a set of points (represented by complex values), and I need to find the shortest path through these. It looks a bit like the travelling salesman problem, but I can't seem to find (or understand) a solution that isn't in O(n!). I know how to compute short enough solutions in O(n^3), O(n²), but I wanted to know if it was possible to have THE best one. Thank you !
There's the code I use for a "Short Enough Path"
def insert(x,liste,taille):
max_add = 10**9
n = len(liste) -1
for i in range(n):
test = abs(liste[i] -x) + abs(liste[i+1] - x) - taille[i]
if test < max_add:
max_add = test
i_max = i
taille[i_max] = abs(liste[i_max]-x)
taille.insert(i_max+1,abs(liste[i_max+1] - x))
liste.insert(i_max+1,x)
def sort(x,i=0):
taille = [0]
tri = [x[i]]*2
for y in x[:i]+x[i+1:]:
inserer(y,tri,taille)
return tri, taille
def the_best(liste):
n = len(liste)
shortest = 10**9
for i in range(n):
a,b = sort(liste,i)
if sum(b) < shortest:
back = a,b
return back
`
Of course the "the_best" function is in O(n^3) so I usually use the "sort" function only
The list called "taille" is built like this:
taille[i] = abs(liste[i] - liste[i+1])
liste[-1] = liste[0]
From what I understand in your description, this is indeed the TSP problem. It is a well-known NP-hard problem, and as such an efficient algorithm to solve it does not exist (even if it does, we don't know of it yet). It's one of the famous open problems in Computer Science.
Indeed, do give it a try to solve it, but do not hold your breath :)
General reading: https://en.wikipedia.org/wiki/Travelling_salesman_problem
You may also want to give a quick read to: https://en.wikipedia.org/wiki/P_versus_NP_problem

Execution timed out (12000ms) kata Generate Numbers from Digits #2 on Code Wars (Python)

Could you give me a hint where the time consuming part of this code is?
It's my temporary solutions for the kata Generate Numbers from Digits #2 from codewars.com.
Thanks!
from collections import Counter
from itertools import permutations
def proc_arrII(arr):
length = Counter(arr).most_common()[-1][1]
b = [''.join(x) for x in list(set(permutations(arr,length)))]
max_count = [max(Counter(x).values()) for x in b]
total = 0
total_rep = 0
maximum_pandigit = 0
for i in range(len(b)):
total+=1
if max_count[i] > 1:
total_rep+=1
elif int(b[i]) > maximum_pandigit:
maximum_pandigit = int(b[i])
if maximum_pandigit == 0:
return([total])
else:
return([total,total_rep,maximum_pandigit])
When posting this,
it would have been helpful to offer example input,
or link to the original question,
or include some python -m cProfile output.
Here is a minor item, it inflates the running time very very slightly.
In the expression [''.join(x) for x in list(set(permutations(arr, length)))]
there's no need to call list( ... ).
The join just needs an iterable, and a set works fine for that.
Here is a bigger item.
permutations already makes the promise that
"if the input elements are unique, there will be no repeat values in each permutation."
Seems like you want to dedup (with set( ... )) on the way in,
rather than on the way out,
for an algorithmic win -- reduced complexity.
The rest looks nice enough.
You might try benching without the elif clause,
using the expression max(map(int, b)) instead.
If there's any gain it would only be minor,
turning O(n) into O(n) with slightly smaller coefficient.
Similarly, you should just assign total = len(b) and be done with it,
no need to increment it that many times.

Can't assign to function call syntax error when trying to subtract variables in python

I'm attempting to create a rudimentary stock trading algorithm. One thing included in that algorithm is, after deciding how many of a stock to buy, subtracting the correct amount of money from the user's total. The problem occurs on the line "int(money_data) -= int(round(float(stockamounts[i]) * float(prices[i])))". The syntax error points to "int(money_data). "I hope I explained the problem in a way that makes sense. Thank you for any help.
for i in stock_symbols:
stock_url = "https://www.nasdaq.com/symbol/" + str(i)
stock_data = requests.get(stock_url)
file = open("data.txt", "w")
file.write(str(stock_data.content))
file.close()
file = open("data.txt", "r")
stock_data = file.read()
file.close()
stock_data = re.findall(r'<div id="qwidget_lastsale" class="qwidget-dollar">(.*?)</div>', str(stock_data))
for i in stock_data:
print(str(i.strip('$')))
price = i.strip('$')
prices.append(price)
stock_amounts = []
print(str(stock_symbols[0]) + " | " + str(round(float(money_amount) / float(prices[0]))))
stock_amounts.append(round(float(money_amount) / float(prices[0])))
for x in range(len(prices)):
print(str(stock_symbols[x]) + " | " + str(round(float(money_amount) / float(prices[x]))))
stock_amounts.append(round(float(money_amount) / float(prices[x])))
print(len(stock_amounts))
for i in stock_amounts:
print(stock_amounts[i])
int(money_data) -= int(round(float(stock_amounts[i]) * float(prices[i])))
print(money_data)
As the error says, you
can't assign to [a] function call
Why?
Say you have a function f:
>>> def f(x);
... return 3*x+4
When you
>>> f(4) = 5
what do you actually mean? You can't logically explain what should happen in a case like this, because basically (and in this example), that's like saying 16 = 5, which, I hope you agree, doesn't make sense.
"But, I did something different"
Yes, you used a variable in the call and used the -= operator.
Still, the a -= b operator is short for a = a-b (although you could overload them to do different stuff), and that's clearly an assignment (even if you overload, it remains an assignment).
How do I fix this?
You have two (and a half) possibilities:
use a normal assignment: just expand to a longer form as in val = int(val-to_sub)
add an extra line val -= to_sub; val = int(val) (please actually add an extra line and don't use ;)
(1/2) leave the int() away. If you are careful to only add, subtract, multiply with or divide through ints (or use // for divisions), you are sure that the value stays an int

How to give a Subclip a new name in Python using PyAutoGUI?

Complete beginner here making my first program with PyAutoGui as I cannot get access to the software's API. My issues are currently being that I am unable to come up with a solution to name each subclip with a different appended letter on the end. The naming convention should go like so, MI899001~AA, MI899001~AB, MI899001~AC, MI899001~AD. The only thing that changes is the last letter.
Below is the relevant code I'm currently using for the program I am writing;
def naming_promo():
x = string.ascii_uppercase
pyautogui.typewrite('DNH~P336007A' + x[0][0])
for i in range(7):
if i == 0:
sub_clip_clean()
else:
if i >= 1:
pyautogui.typewrite('567890qwe', 0.2)
sub_clip_package()
naming_promo() # See above Fn for method
pyautogui.moveTo(646, 404, duration=0.50)
pyautogui.click()
move_clips()
The naming_promo() takes the ascii_uppercase and types the first letter. I however can't figure out how to iterate through each character in the string as the For Loop repeats. I've googled many solutions, but I guess I can't get my head around how to do a loop in a loop and increment the x value used each time.
This is my first post so apologies for any etiquette I break. Any help and explanation would be greatly appreciated.
This is my first answer so apologies for any etiquette I break.
I'm not sure I understand everything here, since there's a few functions in the code that I don't know about. However, are you just looking for something like:
def naming_promo(n):
x = string.ascii_uppercase
pyautogui.typewrite('DNH~P336007A' + x[0][n])
and further down in your code, simply create a variable and increment it up one after use:
m = 0
for i in range(7):
if i == 0:
sub_clip_clean()
else:
if i >= 1:
pyautogui.typewrite('567890qwe', 0.2)
sub_clip_package()
naming_promo(m) # See above Fn for method
m += 1
pyautogui.moveTo(646, 404, duration=0.50)
pyautogui.click()
move_clips()

make a function that take an integer and reduces it down to an odd number

I'm working on my final for a class I'm taking(Python 3) im stuck at this part.
he gave us a file with numbers inside of it. we opened it and add those numbers to a list.
"Create a function called makeOdd() that returns an integer value. This function should take in any integer and reduce it down to an odd number by dividing it in half until it becomes an odd number.
o For example 10 would be cut in half to 5.
o 9 is already odd, so it would stay 9.
o But 12 would be cut in half to 6, and then cut in half again to 3.
o While 16 would be cut to 8 which gets cut to 4 which gets cut to 2 which gets cut to 1.
 Apply this function to every number in the array. "
I have tried to search the internet but i have not clue where to even begin with this one. any help would be nice.
Here my whole final so far:
#imports needed to run this code.
from Final_Functions import *
#Defines empty list
myList = []
sumthing = 0
sortList = []
oddList = []
count = 0
#Starts the Final Project with my name,class, and quarter
intro()
print("***************************************************************",'\n')
#Opens the data file and reads it then places the intrager into a list we can use later.
with open('FinalData.Data', 'r') as f:
myList = [line.strip() for line in f]
print("File Read Complete",'\n')
#Finds the Sum and Adverage of this list from FinalData.Data
print("*******************sum and avg*********************************")
for oneLine in myList:
tempNum = int(oneLine)
sumthing = sumthing + tempNum
avg = sumthing /1111
print("The Sum of the List is:",sumthing)
print("The Adverage of the List is:",avg,'\n')
print("***************************************************************",'\n')
#finds and prints off the first Ten and the last ten numbers in the list
firstTen(myList)
lastTen(myList)
print("***************************************************************",'\n')
#Lest sort the list then find the first and last ten numbers in this list
sortList = myList
sortList.sort()
firstTen(sortList)
lastTen(sortList)
print("****************************************************************",'\n')
Language:Python 3
I don't want to give you the answer outright, so I'm going to talk you through the process and let you generate your own code.
You can't solve this problem in a single step. You need to divide repeatedly and check the value every time to see if it's odd.
Broadly speaking, when you need to repeat a process there are two ways to proceed; looping and recursion. (Ok, there are lots, but those are the most common)
When looping, you'd check if the current number x is odd. If not, halve it and check again. Once the loop has completed, x will be your result.
If using recursion, have a function that takes x. If it's odd, simply return x, otherwise call the function again, passing in x/2.
Either of those methods will solve your problem and both are fundamental concepts.
adding to what #Basic said, never do import * is a bad practice and is a potential source of problem later on...
looks like you are still confuse in this simple matter, you want to given a number X reduce it to a odd number by dividing it by 2, right? then ask yourself how I do this by hand? the answer is what #Basic said you first ask "X is a even number?" if the answer is No then I and done reducing this number, but if the answer is Yes then the next step dividing it by 2 and save the result in X, then repeat this process until you get to the desire result. Hint: use a while
to answer your question about
for num in myList:
if num != 0:
num = float(num)
num / 2
the problem here is that you don't save the result of the division, to do that is as simple as this
for num in myList:
if num != 0:
num = float(num)
num = num / 2

Resources