I am trying to use the Abaqus (a commercial FEA code) scripting interface to generate FE models, although my question is relating to Python specifically, but a bit of background on why I am trying to do this.
Abaqus has a built in boolean merge operation that requires the following syntax to be used:
a.InstanceFromBooleanMerge(name='name_string', instances=(
a.instances['string1'], a.instances['string2'],
a.instances['string3'], ), originalInstances=SUPPRESS,
domain=GEOMETRY)
The 'instances' parameter is specified as a tuple where each element is of the format
a.instances['string1']
I am trying to make it so that the number of elements within this tuple, and obviously the names within it are scriptable. Currently I have code which looks like:
my_list = []
for i in range(4):
name = str('a.instances[\'')+str('name_')+str(i)+str('\']')
my_list.append(name)
my_list = tuple(my_list)
print my_list
However, this gives:
("a.instances['name_0']", "a.instances['name_1']", "a.instances['name_2']",
a.instances['name_3']")
I have tried using lstrip and rstrip to remove the " characters but to no avail. Is there a way of generating a tuple of arbitrary length where the elements are not enclosed in inverted commas? The format is specified by the Abaqus interface, so there is no alternative format that can be used.
Many Thanks
You're close, try:
for i in range(4):
val = a.instances["name_"+str(i)]
my_list.append(val)
You can make this even shorter using a generator expression:
my_list = tuple(a.instances["name_"+str(i)] for i in range(4))
Those characters will be printed out simply because you're printing out a tuple - that means strings will be quoted, so you can see the difference between (123,) and ("123",). If you want to have it without quotes, construct the output yourself:
def make_tuple_of(n):
return '(' + ', '.join("a.instances['name_" + str(i) + "']" for i in range(n)) + ')'
Edit: I thought you actually wanted to generate the code itself, not create tuple in the current code. If generating a tuple in current code is what you actually want to do, just use tuple(a.instances['name_' + str(i)] for i in range(n))
Edit2: Actually, you could check the library you're working with. Unless it specifically tests for tuples for some reason, it accept lists just fine, since the interface for both is pretty much the same. If it does, you could just pass it [a.instances['name_' + str(i)] for i in range(n)] as a parameter and be done.
Related
I was trying to solve up a problem that was going on cause my IDE could not retain a sequence of numbers cause of the range function which works as so.
And i made a Previous question about it so this is a follow-up to the question. Here's my list comment on the previous question.
I actually made some adjustments by adding a line; 'My_list = list(range(100)) before applying your code so it actually worked. But it combines the answers without commas, for example 10 does this '0123456789' instead of '0,1,2,3,4,5,.....8,9'. any suggestions?
I decided to post this question not to allow the other question go out of context (as i was advised to).
Any suggestions?
You need to understand how strings works in Python.
Strings are constants (literals) kept in a closed bucket. In official docs you can find that "Strings are immutable sequences of Unicode code points".
But programmers need to change or manipulate text in a programmable way. In your case you want:
"[x1][space][comma][x2][comma]...[xn][space][comma]"
where "xn" is a number, and " ," is constant.
In order to achieve this, in a programmable way, programmers can use "masks" to tell the software where they want to place their changes. One can use string format operators:
"%d , %f" %(my_first_integer, my_float)
[0][1][2][3][4][\0]
# Hey Python, return a string, using the above template,
# but place useful stuff where you find magic keywords.
Which means:
Create a 6 positions sequence;
In [0], place my_integer of type int converted into chr;
In [1], copy " ";
In [2], copy ",".
In [3], copy " ";
In [4], place my_float of type float converted into chr;
In [5], place "\0" so the string is over. (Automatically placed in Python)
There are other ways to do this, i.e., the string object has a handy method called formatto handle this construction:
my_integer = 2
my_string = "{0}*pi = {1}".format(my_integer, my_integer*3.14)
print(my_string)
# 2*pi = 6.28
The programmer will achieve the same final result using one or another startegy.
In Python, as well as in other languages, one can combine strings, concatenate, get sub-strings and so on, using specific methods and/or operators.
In order to keep readability you maybe (I guess) want to place each value in a line. In strings you can use special characters like \n for new lines.
my_list = list(range(100))
# ... useful code here and there ...
with open("output.txt", "w") as o:
o.write("My list:\n")
o.write("\tSize: {0}\n\n".format(len(my_list)))
o.write("\t----start----\n")
for i in range(len(my_list)):
o.write("%d\n" % my_list[i])
o.write("\n\t----end----\n")
# That writes:
# My list:
# Size: 100
#
# ----start----
# 0
# 1
# 2
# 3
...
# 99
#
# ----end----
Remember, this is not a comprehensive guide, but a layman one. I'm skipping a lot of boring words and technical details that you'll better find in Python books and courses.
You just need to insert a comma after printing each number:
my_list = list(range(100))
with open("output.txt", "w") as o:
for i in range(len(my_list)):
o.write("%d," % my_list[i]) # Here, after '%d' you can place a comma, or any text you want
I'm looking to write a piece of code in Javascript or Python that generates a wordlist file out of a pre-defined combination of characters.
E.g.
input = abc
output =
ABC
abc
Abc
aBc
abC
AbC
ABc
aBC
I have very basic knowledge of either so all help is appreciated.
Thank you
I'll assume that you're able to import Python packages. Therefore, take a look at itertools.product:
This tool computes the cartesian product of input iterables.
For example, product(A, B) returns the same as ((x,y) for x in A for y in B).
It looks quite like what you're looking for, right? That's every possible combination from two different lists.
Since you're new to Python, I'll assume you don't know what a map is. Nothing too hard to understand:
Returns a list of the results after applying the given function to each item of a given iterable (list, tuple etc.)
That's easy! So the first parameter is the function you want to apply and the second one is your iterable.
The function I applied in the map is as follows:
''.join
This way you set '' as your separator (basically no separator at all) and put together every character with .join.
Why would you want to put together the characters? Well, you'll have a list (a lot of them in fact) and you want a string, so you better put those chars together in each list.
Now here comes the hard part, the iterable inside the map:
itertools.product(*((char.upper(), char.lower()) for char in string)
First of all notice that * is the so-called splat operator in this situation. It splits the sequence into separate arguments for the function call.
Now that you know that, let's dive into the code.
Your (A, B) for itertools.product(A, B) are now (char.upper(), char.lower()). That's both versions of char, upper and lowercase. And what's char? It's an auxiliar variable that will take the value of each and every character in the given string, one at a time.
Therefore for input 'abc' char will take values a, b and c while in the loop, but since you're asking for every possible combination of uppercase and lowercase char you'll get exactly what you asked for.
I hope I made everything clear enough. :)
Let me know if you need any further clarification in the comments. Here's a working function based on my previous explanation:
import itertools
def func():
string = input("Introduce some characters: ")
output = map(''.join, itertools.product(*((char.upper(), char.lower()) for char in string)))
print(list(output))
As an additional note, if you printed output you wouldn't get your desired output, you have to turn the map type into a list for it to be printable.
A simple approach using generators, and no library code. It returns a generator (iterator-like object), but can be converted to a list easily.
def lU(s):
if not s:
yield ''
else:
for sfx in lU(s[1:]):
yield s[0].upper() + sfx
yield s[0].lower() + sfx
print list(lU("abc"))
Note that all the sub-lists of suffixes are not fully expanded, but the number of generator objects (each a constant size) that get generated is proportional to the length of the string.
Disclaimer: The question how to print a list in python is already covered multiple times, thus, this question does NOT ask HOW to print a list BUT WHETHER a specific way to print a list exists (using the format directive).
The first hit one gets googling how to print a list using format in python is here and it looks like:
print('\n'.join('{}'.format(k) for k in lst))
is the way to go. But I keep wondering if there is a lisp like format directive to do this without the verbose join operation. E.g. in common lisp one would simple write:
(FORMAT T "~%~{~a~%~}" list-i-want-printed)
~{...~} basically means iterate over list
~a basically means to take one argument and print it using its (or the default) print/to-string directive
~% newline
Does such a format directive exist in python?
As a more thorough example why I'd like to use such directive:
Given you have 3 lists you want to print below each other. The lisp FORMAT would allow:
(FORMAT T "~{~a~}~%~{~a~}~%~{~a~}~%" list-1 list-2 list-3)
whereas the python solution would look like:
print(''.join('{}'.format(k) for k in lsta) + '\n' + ''.join('{}'.format(k) for k in lstb) + '\n' + ''.join('{}'.format(k) for k in lstc))
not quite as refined.
I think the basic answer is "No", but you can refine your example a bit:
print( ' '.join( '{}'.format(k) for k in lsta+lstb+lstc ) )
No newlines. If I wanted a newline after each list I'd do
for lst in (lsta,lstb,lstc):
print( ' '.join( '{}'.format(k) for k in lst ) )
I have a Python list that looks like the below:
list = ['|wwwwwwwwadawwwwwwwwi', '|oooooooocFcooooooooi']
I access the letter in the index I want by doing this:
list[y][x]
For example, list[1][10] returns F.
I would like to replace F with a value. Thus changing the string in the list.
I have tried list[y][x] = 'o' but it throws the error:
self.map[y][x] = 'o'
TypeError: 'str' object does not support item assignment
Can anybody help me out? Thanks.
As #Marcin says, Python strings are immutable. If you have a specific character/substring you want to replace, there is string.replace. You can also use lists of characters instead of strings, as described here if you want to support the functionality of changing one particular character.
If you want something like string.replace, but for an index rather than a substring, you can do something like:
def replaceOneCharInString(string, index, newString):
return string[:index] + newString + string[index+len(newString):]
You would need to do some length checking, though.
Edit: forgot string before the brackets on string[index+len(newString):]. Woops.
Since python strings are immutable, they cannot be modified. You need to make new ones. One way is as follows:
tmp_list = list(a_list[1])
tmp_list[10] = 'o' # simulates: list[1][10]='o'
new_str = ''.join(tmp_list)
#Gives |oooooooococooooooooi
# substitute the string in your list
a_list[1] = new_str
As marcin says, strings are immutable in Python so you can not assign to individual characters in an existing string. The reason you can index them is that thay are sequences. Thus
for c in "ABCDEF":
print(c)
Will work, and print each character of the string on a separate line.
To achieve what you want you need to build a new string.For example, here is a brute force approach to replacing a single character of a string
def replace_1(s, index, c)
return s[:index] + c + s[index+1:]
Which you can use thus:
self.map[y] = replace_1(self.map[y], x, 'o')
This will work because self.map is list, which is mutable by design.
Let use L to represent the "list" since list is a function in python
L= ['|wwwwwwwwadawwwwwwwwi', '|oooooooocFcooooooooi']
L[1]='|oooooooococooooooooi'
print(L)
Unfortunately changing a character from an object (in this case) is not supported. The proper way would be to remove the object and add a new string object.
Output
['|wwwwwwwwadawwwwwwwwi', '|oooooooococooooooooi']
This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 20 days ago.
I am familiar with the input() function, to read a single variable from user input. Is there a similar easy way to read two variables?
I'm looking for the equivalent of:
scanf("%d%d", &i, &j); // accepts "10 20\n"
One way I am able to achieve this is to use raw_input() and then split what was entered. Is there a more elegant way?
This is not for live use. Just for learning..
No, the usual way is raw_input().split()
In your case you might use map(int, raw_input().split()) if you want them to be integers rather than strings
Don't use input() for that. Consider what happens if the user enters
import os;os.system('do something bad')
You can also read from sys.stdin
import sys
a,b = map(int,sys.stdin.readline().split())
I am new at this stuff as well. Did a bit of research from the python.org website and a bit of hacking to get this to work. The raw_input function is back again, changed from input. This is what I came up with:
i,j = raw_input("Enter two values: ").split()
i = int(i)
j = int(j)
Granted, the code is not as elegant as the one-liners using C's scanf or C++'s cin. The Python code looks closer to Java (which employs an entirely different mechanism from C, C++ or Python) such that each variable needs to be dealt with separately.
In Python, the raw_input function gets characters off the console and concatenates them into a single str as its output. When just one variable is found on the left-hand-side of the assignment operator, the split function breaks this str into a list of str values .
In our case, one where we expect two variables, we can get values into them using a comma-separated list for their identifiers. str values then get assigned into the variables listed. If we want to do arithmetic with these values, we need to convert them into the numeric int (or float) data type using Python's built-in int or float function.
I know this posting is a reply to a very old posting and probably the knowledge has been out there as "common knowledge" for some time. However, I would have appreciated a posting such as this one rather than my having to spend a few hours of searching and hacking until I came up with what I felt was the most elegant solution that can be presented in a CS1 classroom.
Firstly read the complete line into a string like
string = raw_input()
Then use a for loop like this
prev = 0
lst = []
index = 0
for letter in string :
if item == ' ' or item == '\n' :
lst.append(int(string[prev:index])
prev = index + 1
This loop takes a full line as input to the string and processes the parts in it individually and then appends the numbers to the list - lst after converting them to integers .
you can read 2 int values by using this in python 3.6.1
n,m = map(int,input().strip().split(" "))
You can also use this method for any number of inputs. Consider the following for three inputs separated by whitespace:
import sys
S = sys.stdin.read()
S = S.split()
S = [int(i) for i in S]
l = S[0]
r = S[1]
k = S[2]
or you can do this
input_user=map(int,raw_input().strip().split(" "))
You can use this method for taking inputs in one line
a, b = map(int,input().split())
Keep in mind you can any number of variables in the LHS of this statement.
To take the inputs as string, use str instead of int
And to take list as input
a = list(map(int,input.split()))
in python 3.9 , use a, b = map(int,input().split())
because you will get raw_input() not defined