DashInsert 함수는 숫자로 구성된 문자열을 입력받은 뒤, 문자열 내에서 홀수가 연속되면 두 수 사이에 - 를 추가하고, 짝수가 연속되면 * 를 추가하는 기능을 갖고 있다. (예, 454 => 454, 4546793 => 454*67-9-3) DashInsert 함수를 완성하자. 출처
"4546793"
"454*67-9-3"
205개의 풀이가 있습니다.
#파이썬3.5.2
i = list(map(int,' '.join(input()).split()))
answer = [str(i[0])]
for x in range(len(i)-1):
if i[x]%2==0 and i[x+1]%2==0:
answer.append('*')
if i[x]%2==1 and i[x+1]%2==1:
answer.append('-')
answer.append(str(i[x+1]))
print(''.join(answer))
입력:
4546793
출력:
454*67-9-3
파이썬
def dashInsert(listInput):
resultStr = ""
for i in range(len(listInput)):
if i > 0:
if int(listInput[i-1]) % 2 == 0 and int(listInput[i]) % 2 == 0:
resultStr += "*"
elif int(listInput[i-1]) % 2 == 1 and int(listInput[i]) % 2 == 1:
resultStr += "-"
resultStr += listInput[i]
return(resultStr)
inputStr = "4546793"
print(dashInsert(inputStr))
Java
import java.util.function.UnaryOperator;
public class DashInsert {
public static UnaryOperator<Integer> oddOrEven = i -> i % 2 == 0 ? 1:-1;
public static UnaryOperator<String> dashInsert = s -> {
int beforeState = 0;
int currentState = 0;
String result = "";
for (int i = 0; i < s.length(); i++) {
currentState = oddOrEven.apply(Character.getNumericValue(s.charAt(i)));
if (currentState == beforeState) {
if (currentState == 1) {
result += "*";
} else {
result += "-";
}
}
beforeState = currentState;
result += Character.toString(s.charAt(i));
}
return result;
};
public static void main(String[] args) {
System.out.println(dashInsert.apply("112234566778"));
}
}
re.sub 에 matchobj 을 인자로하는 함수사용이 가능하단걸 최근에 알았네요.
test = "4546793"
import re
def testfunc(mo):
try:
return '-'.join(mo.group(1))
except:
return '*'.join(mo.group(2))
result=re.sub('([13579]{2,})|([24680]{2,})',testfunc,test)
print(result)
a="4546793"
b=[]
for i in range(0,len(a)-1):
if (int(a[i])%2==0 and int(a[i+1])%2==0) : #짝수연속
b.append(a[i]+"*")
elif (int(a[i])%2==1 and int(a[i+1])%2==1) : #홀수연속
b.append(a[i]+"-")
else :
b.append(a[i])
print("".join(b)+a[len(a)-1])
454*67-9-3
# 한글 처리 in Atom 1.21.1 + Anaconda(Python 3.6.3)
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding='utf-8')
# DashInsert 함수는 숫자로 구성된 문자열을 입력받은 뒤,
# 문자열 내에서 홀수가 연속되면 두 수 사이에 - 를 추가하고,
# 짝수가 연속되면 * 를 추가하는 기능을 갖고 있다.
# (예, 454 => 454, 4546793 => 454*67-9-3)
# DashInsert 함수를 완성하자.
num = input()
# num = '4546793'
dashinsert = num[0]
for i in range(len(num) - 1):
if int(num[i]) % 2 and int(num[i + 1]) % 2:
dashinsert += '-'
elif not(int(num[i]) % 2) and not(int(num[i + 1]) % 2):
dashinsert += '+'
dashinsert += num[i + 1]
print(dashinsert)
import java.util.Scanner;
import java.util.ArrayList;
public class DashInsert {
public static void main(String[] args) {
Scanner Sc = new Scanner(System.in);
ArrayList<String> num = new ArrayList<String>();
System.out.print("숫자를 입력하시오 :");
String input = Sc.nextLine();
String[] array = input.split("");
for(int l = 0; l<array.length; l++) {
num.add(l,array[l]);
}
for(int k = 0; k<num.size()-1; k++) {
if(num.get(k).contentEquals("-")||num.get(k).contentEquals("*")) {
continue;
}
else if(Integer.parseInt(num.get(k))%2 == 0 && Integer.parseInt(num.get(k+1))%2 == 0) {
num.add(k+1,"*");
}
else if(Integer.parseInt(num.get(k))%2==1 && Integer.parseInt(num.get(k+1))%2 == 1) {
num.add(k+1,"-");
}
}
for(String j : num) {
System.out.print(j);
}
Sc.close();
}
}
class FinalInserter:
def __init__(self):
self.result = ""
def insertMark(self,n):
l = str(n)
self.result = l[0]
for i in range(1,len(l)):
if int(l[i-1])%2==1 and int(l[i])%2==1:
self.result += "-"
self.result += l[i]
elif int(l[i-1])%2==0 and int(l[i])%2==0:
self.result += "*"
self.result += l[i]
else:
self.result += l[i]
return self.result
a = FinalInserter()
b = a.insertMark(454)
print(b)
b = a.insertMark(4546793)
print(b)
a = input()
b=''
for i in range(len(a)-1):
b+=a[i]
if (int(a[i])+int(a[i+1]))%2==0:
if int(a[i])%2==0:
b+='*'
else:
b+='-'
b+=a[len(a)-1]
print(b)
def DashInsert(ui):
result = "%s" % ui[0]
for i in range(len(ui)-1):
if int(ui[i])%2 == 0 and int(ui[i+1])%2 == 0:
result += '*'
elif int(ui[i])%2 == 1 and int(ui[i+1])%2 == 1:
result += '-'
result += ui[i+1]
return result
ui = input("숫자로 구성된 문자열 입력>> ")
print(DashInsert(ui))
function dashInsert(input){
var res = '';
for(var i = 0; i < input.length - 1; i++){
res += input[i];
if(input[i] % 2 == 0 && input[i+1] % 2 == 0){
res += '*';
} else if(input[i] % 2 == 1 && input[i+1] % 2 == 1){
res += '-';
}
}
res += input[i];
return res;
}
def Dash_Insert(s):
st=""
for i in range(1,len(s)):
st+=s[i-1]
if((ord(s[i-1])-ord('0'))%2==0 and (ord(s[i])-ord('0'))%2==0):
st+='*'
elif((ord(s[i-1])-ord('0'))%2!=0 and (ord(s[i])-ord('0'))%2!=0):
st+='-'
st+=s[i]
print st
Dash_Insert("1324924")
for문을 이용해 문자열을 탐색하여 홀수인 경우+ 짝수인 경우 *를 추가하도록 했습니다.
결과:1-32*492*4
Ruby
def dash_insert
puts gets.chop.chars.chunk {|_|_.to_i%2}.sum("") {|(i,e)| e*"*-"[i]}
end
Test
$stdin = StringIO.new("4546793\n")
expect{ dash_insert() }.to output("454*67-9-3\n").to_stdout
Output
dash_insert
4546793
454*67-9-3
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
string DashInsert(void);
int main(void) {
string str;
cout << "input number : ";
str = DashInsert();
cout << str << endl;
return 0;
}
string DashInsert(void) {
string str;
string temp_str;
string str_temp[2];
string return_str;
int temp[2] = { 0,0 };
cin >> str;
for (int i = 0;i<str.length()-1;i++) {
str_temp[0] = str[i];
str_temp[1] = str[i+1];
temp[0] = atoi(str_temp[0].c_str());
temp[1] = atoi(str_temp[1].c_str());
if (temp[0] % 2 == 0 && temp[1] % 2 == 0) {
temp_str = "*";
}
else if (temp[0] % 2 == 1 && temp[1] % 2 == 1) {
temp_str = "-";
}
return_str += str[i];
return_str += temp_str;
temp_str = "";
}
return_str += str[str.length()-1];
return return_str;
}
public class Main {
public static void main(String[] args) {
String str = args[0];
DashInsert dashInsert = new DashInsert();
StringBuffer result = dashInsert.dashInsert(str);
System.out.print(result);
}
}
public class DashInsert {
public StringBuffer dashInsert(String str) {
StringBuffer newStr = new StringBuffer();
String temp = str;
int p = -1;
int q = -1;
newStr.append(""+temp.charAt(0));
for(int i=1; i<temp.length(); i++) {
p = Integer.parseInt(""+temp.charAt(i-1));
q = Integer.parseInt(""+temp.charAt(i));
if((p%2==0)&&(q%2==0))
newStr.append("*"+q);
else if((p%2!=0)&&(q%2!=0))
newStr.append("-"+q);
else
newStr.append(""+q);
}
return newStr;
}
}
package codingdojang;
public class DashInsert
{
enum NUM
{
EVEN,
ODD,
NOT
}
private static String dashInsert(String num)
{
StringBuffer result = new StringBuffer();
for ( int i = 0; i < num.length() - 1; i++ )
{
int firstDigit = Integer.parseInt( num.charAt( i ) + "" );
int secondDigit = Integer.parseInt( num.charAt( i + 1 ) + "" );
result.append( firstDigit );
switch ( isInsertDash( firstDigit, secondDigit) )
{
case EVEN:
result.append( "*" );
break;
case ODD:
result.append( "-" );
break;
default:
break;
}
}
result.append( num.charAt( num.length()-1 ) );
return result.toString();
}
private static NUM isInsertDash( int firstDigit, int secondDigit )
{
if ( isEven( firstDigit ) && isEven( secondDigit ) )
{
return NUM.EVEN;
}
else if ( !isEven( firstDigit) && !isEven( secondDigit ))
{
return NUM.ODD;
}
else
{
return NUM.NOT;
}
}
private static boolean isEven( int firstDigit )
{
return firstDigit % 2 == 0;
}
public static void main( String[] args )
{
String num = "4546793";
String result = dashInsert( num );
System.out.println( result );
}
}
#include <stdio.h>
void dashInsert(char *nstr)
{
int past = 3;
for (; *nstr != NULL; nstr++)
{
if (past == (*nstr - '0') % 2 & past == 1)
printf("-");
else if (past == (*nstr - '0') % 2 & past == 0)
printf("*");
printf("%c", *nstr);
past = (*nstr - '0') % 2;
}
}
int main()
{
char str[20];
scanf("%s", str);
dashInsert(str);
return 0;
}
function DashInsert(input) {
var str = "",
past = undefined;
for (var c of input) {
c = parseInt(c); //문자열 -> 숫자 변환
if (past && (c % 2 == past % 2)) { //앞뒤로 비교
if (c % 2 == 1) //홀수인가
str += '-';
else //짝수인가
str += '*'; //구분자 넣고
}
str += c; //원래 들어갈 문자 넣고
past = c; //다음 비교를 위해 저장
}
console.log(str);
}
zip함수를 이용했습니다.
is_even = lambda a, b: int(a)%2==0 and int(b)%2==0
is_odd = lambda a, b: int(a)%2 != 0 and int(b)%2 != 0
def f(s):
c = s[0]
for a, b in zip(s, s[1:]):
if is_even(a, b):
c += '*' + b
elif is_odd(a, b):
c += '-' + b
else:
c += b
return c
a = '4546793'
a_ = '454*67-9-3'
assert f(a) == a_
def f(x):
res = ''
for i in range(len(x)-1):
a, b = int(x[i])%2, int(x[i+1])%2
res += x[i] + (('-' if a == 1 else '*') if a == b else '')
return res + x[-1]
while __name__ == '__main__':
print(f(input('>>>')))
파이썬 3.5.2 64
파이썬입니다.
def do(ls):
xs = [int(x) for x in ls]
result = xs[:1]
for i, x in enumerate(xs[1:]):
if (xs[i] + x) % 2 == 0:
result.append('*' if x % 2 is 0 else '-')
result.append(x)
return ''.join([str(x) for x in result])
print(do(input())
왕초보가 만든 자바풀이(믿거나 말거나#2) 푸는데 5시간걸림 ㅠ.ㅠ <풀이> 1. 입력받은 숫자를 문자열 배열로 2. 문자열은 홀수/짝수 확인이 안됨으로 문자열 배열은 정수 배열로 변환 3. 정수 배열은 값에 대한 수정이 안됨으로 List로 바꿈 4. 홀수 혹은 짝수 사이에 임의의 두 수(-부호)를 첨가함. 5. 임의의 수를 와 -로 변경해야하는데 정수List라 안되서 단지 문자열 List로 전환 6. 변경된 문자열 List에서 임의의 두 수를 찾아 와 -로 변경한 후 출력함
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("일련된 정수를 임의대로 공백없이 나열하시오. ");
List<String> list=Arrays.asList(sc.nextLine().split(""));
List<Integer> intList=new ArrayList<Integer>();
for(String s : list)
intList.add(Integer.valueOf(s));
for(int i=1;i<=list.size()+1;i++) {
if(intList.get(i-1)%2==0&&intList.get(i)%2==0)
intList.add(i,-1);
if(intList.get(i-1)%2==1&&intList.get(i)%2==1)
intList.add(i,-2);
}
List<String> strList=new ArrayList<String>();
for(int s : intList)
strList.add(String.valueOf(s));
for(int i=0;i<strList.size();i++) {
if(strList.contains("-1"))
strList.set(strList.indexOf("-1"),"*");
if(strList.contains("-2"))
strList.set(strList.indexOf("-2"),"-");
}
for(int i=0;i<strList.size();i++)
System.out.print(strList.get(i));
sc.close();
}
코드의 문제점 : *는 5번, -는 4번이상 안찍임.. 예1) 8888888888 = 8*8*8*8*8*88888 예2) 7777777777 = 7-7-7-7-777777
package Study;
import java.util.Scanner;
public class Dash_Insert {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
int a=0;
int b=0;
for (int test_case = 1; test_case <= T; test_case++) {
String num = sc.next();
String Dash ="";
for(int i=0 ; i < num.length()-1; i++ ){
a = num.charAt(i) - '0';
b = num.charAt(i+1) - '0';
if(a%2==0 && b%2==0) {
Dash = Dash+ Integer.toString(a)+'*'; //짝수
}else if(a%2==1 && b%2==1) {
Dash = Dash+ Integer.toString(a)+'-'; //홀수
}else{
Dash = Dash+ Integer.toString(a);
}
}
Dash = Dash+ Integer.toString(b);
System.out.println("최종문자 : " + Dash);
}
}
}
홀수-홀수, 짝수*짝수를 출력하려면 현재 읽은 값이 홀수인지 짝수인지 기억해야 한다. 2로 나눈 나머지를 기억하면 된다.
int main(int argc, const char * argv[]) {
int c;
int state = -1; // -1(시작), 0(짝수), 1(홀수)
while((c = getchar()) != EOF) {
if (c%2 == state) { // 연속된 짝수 혹은 홀수인 경우 추가로 출력할 글자가 있다!
putchar(state ? '-' : '*');
}
putchar(c);
state = c%2;
}
return 0;
}
새줄(\n)을 만나면 리셋해주면 여러줄에 대해 처리할 수 있다.
int main(int argc, const char * argv[]) {
int c;
int state = -1; // -1(시작), 0(짝수), 1(홀수)
while((c = getchar()) != EOF) {
if (c == '\n') { // reset
putchar(c);
state = -1;
continue;
}
if (c%2 == state) {
putchar(state ? '-' : '*');
}
putchar(c);
state = c%2;
}
return 0;
}
public static void main(String[] args){
String dashString = "4546793";
boolean isSame = false;
String newDashString = "";
for(int i = 0; i < dashString.length() - 1; i++){
char char1 = dashString.charAt(i);
char char2 = dashString.charAt(i + 1);
if(Integer.parseInt(Character.toString(char1)) % 2 == 0 && Integer.parseInt(Character.toString(char2)) % 2 == 0) {
newDashString += Character.toString(char1) + "*";
}
else if(Integer.parseInt(Character.toString(char1)) % 2 != 0 && Integer.parseInt(Character.toString(char2)) % 2 != 0){
newDashString += Character.toString(char1) + "-";
}
else {
newDashString += Character.toString(char1);
}
if(i == dashString.length() - 2) {
newDashString += Character.toString(char2);
}
}
System.out.println(newDashString);
}
파이썬
제 풀이는 왜 안될까요? ㅠㅠ
TypeError: not all arguments converted during string formatting 라고 나옵니다..
def Dash(num):
num = list(num)
num_int=[]
for i in num:
num_int.append(int(i))
A = []
A.append(num_int[0])
n = 1
while n <= len(num_int):
if num_int[n]%2==0 and A[n-1]%2==0:
A.append('*')
A.append(num_int[n])
elif num_int[n]%2==1 and A[n-1]%2==1:
A.append('-')
A.append(num_int[n])
elif num_int[n]%2==1 and A[n-1]%2==0:
A.append(num_int[n])
elif num_int[n]%2==0 and A[n-1]%2==1:
A.append(num_int[n])
n += 1
print(A)
Dash('34235')
def dash_insert(num):
for x in range(len(num)-1):
if int(num[x]) % 2 == 0 and int(num[x+1]) % 2 == 0:
num[x] += '*'
elif int(num[x]) % 2 == 1 and int(num[x+1]) % 2 == 1:
num[x] += '-'
return ''.join(num)
print(dash_insert(list(input())))
#### 2016.12.14 D-435 ####
$input = "4546793";
$output = array();
$array = str_split($input);
$sw = 0;
foreach($array as $key => $num){
// 짝수,홀수인지 판별
$dash = ($num%2==0) ? '*' : '-';
if($key!=0 && $array[$key-1]%2 == $num%2) $output[] = $dash;
$output[] = $num;
}
echo join("",$output);
import java.util.Scanner;
public class dashinsert {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("숫자를 입력하세요 : ");
String num = sc.nextLine();
char[] ch = num.toCharArray();
String result = "";
for(int i = 0; i < ch.length-1; i++){
if( ch[i]%2 == 1 && ch[i+1]%2 == 1 ){
result += ch[i] + "-";
} else if (ch[i]%2 == 0 && ch[i+1]%2 == 0){
result += ch[i] + "*";
} else {
result += ch[i];
}
}
result += ch[ch.length-1];
System.out.println("최종결과는 " + result + " 입니다.");
}
}
import java.util.Scanner;
public class dashInsert {
public static void main(String[] args) {
String input;
int first,second,val=0;
StringBuffer inputBuffer;
Scanner scan = new Scanner(System.in);
System.out.println("숫자를 입력하세요 >");
input = scan.next();
inputBuffer = new StringBuffer(input);
for(int i=0;i<input.length()-1;i++,val++){
first = Character.getNumericValue(input.charAt(i));
second = Character.getNumericValue(input.charAt(i+1));
int sum = first +second;
if(sum%2==0){
if(first%2==0){
inputBuffer.replace(val, val+1, input.charAt(i)+"*");
val++;
}
else{
inputBuffer.replace(val, val+1, input.charAt(i)+"-");
val++;
}
}
}
System.out.println(inputBuffer);
}
}
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.IntStream;
public class DashInsert {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] numbers = sc.nextLine().split("");
IntStream.range(0, numbers.length).reduce((a, b) -> {
Integer c = Integer.valueOf(numbers[a]) % 2;
Integer d = Integer.valueOf(numbers[b]) % 2;
if (c == 0 && d == 0) numbers[a] = numbers[a] + "*";
if (c == 1 && d == 1) numbers[a] = numbers[a] + "-";
return b;
});
System.out.println(Arrays.asList(numbers).stream().reduce((a, b) -> a + b).orElse(""));
}
}
def dashinsert(n):
n=str(n)
result=str(n[0])
for i in range(len(n)-1):
if int(n[i])%2==0 and int(n[i+1])%2==0:
result+="*"+str(n[i+1])
elif int(n[i])%2==1 and int(n[i+1])%2==1:
result+="-"+str(n[i+1])
else:
result+=str(n[i+1])
print(result)
public String numOddChecker(String input) {
int preNum = 0;
int nextNum = 0;
String result = "";
preNum = Character.getNumericValue(input.charAt(0)) % 2;
result += input.charAt(0);
for(int i = 1; i <input.length();i++){
nextNum = Character.getNumericValue(input.charAt(i)) % 2;
if(preNum == nextNum){
if(preNum == 0){
result += "*";
}else{
result += "-";
}
}
result += input.charAt(i);
preNum = nextNum;
}
return result;
}
import java.util.*;
public class dashinsert {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String nums = sc.nextLine(); //6539864
String [] array_nums = nums.split(""); //6,5,3,9,8,6,4
ArrayList <String> list_nums = new ArrayList <String>();
for(String i:array_nums){list_nums.add(i);} //["6","5","3","9","8","6","4"]
for(int k=0;k<(array_nums.length)-1;k++){
if(Integer.parseInt(list_nums.get(k))%2==1 && Integer.parseInt(list_nums.get(k+1))%2==1){
list_nums.remove(k);
list_nums.add(k,array_nums[k]+"-");
}
else if(Integer.parseInt(list_nums.get(k))%2==0 && Integer.parseInt(list_nums.get(k+1))%2==0){
list_nums.remove(k);
list_nums.add(k,array_nums[k]+"*");
}
}
String result = "";
for(String l:list_nums){result+=l;}
System.out.println(result);
}
}
N = input("숫자를 입력하시오: ")
def DashInsert(num):
number = ""
for i in range(len(num)-1):
if int(num[i])%2 == 0 and int(num[i+1])%2 == 0:
number += (num[i]+ '*')
elif int(num[i])%2 != 0 and int(num[i+1])%2 != 0:
number += (num[i] + '-')
else: number += num[i]
return number+num[-1]
public void go(String userinput) {
int j=0;
StringBuilder number = new StringBuilder(userinput);
char [] num = userinput.toCharArray();
for(int i=0 ; i<num.length-1 ; i++,j++) {
int a = Integer.parseInt(String.valueOf(num[i]));
int b = Integer.parseInt(String.valueOf(num[i+1]));
if(a%2==0 && b%2==0) {
number.insert(j+1,"*");
j++;
}else if ((a!=0&&b!=0) && (a%2!=0 && b%2!=0)) {
number.insert(j+1, "-");
j++;
}
}
System.out.print(number);
}
}
package training;
/*
* DashInsert 함수는 숫자로 구성된 문자열을 입력받은 뒤, 문자열 내에서 홀수가 연속되면 두 수 사이에 - 를 추가하고, 짝수가 연속되면 * 를 추가하는 기능을 갖고 있다. (예, 454 => 454, 4546793 => 454*67-9-3) DashInsert 함수를 완성하자. 출처
* 입력 - 화면에서 숫자로 된 문자열을 입력받는다.
* "4546793"
* 출력 - *, -가 적절히 추가된 문자열을 화면에 출력한다.
* "454*67-9-3"
*/
public class DashInsert {
public static void main(String[] args) {
String str = "4546793";
char[] ch = str.toCharArray();
StringBuffer sf = new StringBuffer();
for(int i=0;i<ch.length;i++){
if(i == ch.length-1){
sf.append(ch[i]);
break;
}
if(Integer.parseInt(String.valueOf(ch[i])) % 2 == 0 && Integer.parseInt(String.valueOf(ch[i+1])) % 2 == 0){ // 현재수와 다음수가 모두 짝수이면
sf.append(ch[i]+"*");
} else if(Integer.parseInt(String.valueOf(ch[i])) % 2 != 0 && Integer.parseInt(String.valueOf(ch[i+1])) % 2 != 0){ // 현재수와 다음수가 모두 홀수이면
sf.append(ch[i]+"-");
} else {
sf.append(ch[i]);
}
}
System.out.println("Original Text : " + str);
System.out.println("Transfer Text : " + sf);
}
}
def dhin(num):
result=list(num)
result.append('0')
odd=['1','3','5','7','9','-1','-3','-5','-7','-9']
even=['2','4','6','8','*2','*4','*6','*8']
m=0
for i in result:
m=m+1
if i != result[len(result)-1]:
if i in even and result[m] in even:
result[m]='*'+result[m]
if i in odd and result[m] in odd:
result[m]='-'+result[m]
else:
pass
result.pop(-1)
for u in result:
result1=print(u,end='')
return result1
print(dhin("4546793"))
PHP
$val = "4546793";
for($i=strlen($val)-1; $i>0; $i--) {
$a = $val[$i]%2;
$b = $val[$i-1]%2;
if($in = ($a && $b)?'-':((!$a && !$b)?'*':false)) {
$val = substr_replace($val, $in, $i, 0);
}
}
echo $val;
import java.util.Scanner;
public class DashInsertMain {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String num = scanner.nextLine();
StringBuffer stringBuffer = new StringBuffer(num);
//숫자를 String으로 입력받음
boolean prevOdd = false;
boolean currentOdd = false;
int addCount=0;
//addCount : 중간에 String 길이가 늘어나는 것 대처하기 위한 변수
prevOdd = (num.charAt(0)%2 != 0) ? true : false;
//for문 들어가기 전 첫번째 숫자가 홀수인지 먼저 확인
for(int i=1, size=num.length(); i<size; i++){
//첫번째는 이미 확인했으므로 i=0이 아닌 i=1부터.
currentOdd = (num.charAt(i)%2 != 0) ? true : false;
//for문 시작시 currentOdd 정보 입력
if(prevOdd == currentOdd && prevOdd){
//둘 다 홀수일 경우
stringBuffer.insert(i+addCount++, "-");
}else if(prevOdd == currentOdd){
//둘 다 짝수일 경우
stringBuffer.insert(i+addCount++, "*");
}
prevOdd = currentOdd;
//for문 넘기기 전에 prev 정보 입력
}
System.out.println("Output: "+stringBuffer.toString());
}
}
자바로 짜봤어요!
python 3.4.2 입력스트링을 zip()을 사용하여 tuple 로 묶어서 계산했습니다.
in_str = input("Enter numbers: ") # 입력이 4546793 이면 in_str = '4546793'
result = in_str[0]
for a,b in zip(in_str[0:], in_str[1:]): # zip()으로 묶인 튜플은 ('4','5'),('5','4'),('4','6'),('6','7'),('7','9'),('9','3')
if int(a)%2 == 0 and int(b)%2 == 0:
result += '*' + b
elif int(a)%2 == 1 and int(b)%2 == 1:
result += '-' + b
else:
result += b
print(result)
using System;
namespace dashinsert
{
class nana
{
static void Main (string[] args)
{
int num = 0;
Console.WriteLine("{0}, {1}", Math.Pow(2, 3), Math.Pow(3, 2));
while (true)
{
Console.WriteLine("숫자들을 입력하십시오.");
string temp = Console.ReadLine();
try { num = Convert.ToInt32(temp); }
catch (Exception e) { Console.WriteLine("다시 입력하세요. 숫자만 들어가야 합니다.");}
if (num != 0)
break;
}
int memory = 0;
int i = 0;
while (true)
{
if ((int)(num / Math.Pow(10, i)) % 10 != 0)
{
memory = i;
i++;
}
else
break;
}
memory++;
string result = "";
for (int j = memory - 1; j >= 0; j--)
{
result += Convert.ToString((int)(num / Math.Pow(10, j)) % 10);
if (j != 0)
{
if (((int)(num / Math.Pow(10, j)) % 10) % 2 == 0 && (((int)(num / Math.Pow(10, j - 1)) % 10)) % 2 == 0)
result += "*";
if (((int)(num / Math.Pow(10, j)) % 10) % 2 == 1 && (((int)(num / Math.Pow(10, j - 1)) % 10)) % 2 == 1)
result += "-";
}
}
Console.WriteLine(result);
}
}
}
example = '4546793'
examplelist = [int(example[i]) for i in range(len(example))]
def distinguish(objectlist,count):
if ( objectlist[count] + objectlist[count+1] ) % 2 != 1:
if objectlist[count] % 2 == 1:
return 1
else:
return 2
return 0
ilist = list()
for i in range(len(examplelist)-1):
if distinguish(examplelist,i) == 1:
ilist.append([i+1,'-'])
elif distinguish(examplelist,i) == 2:
ilist.append([i+1,'*'])
print(ilist)
for i,x in enumerate(ilist):
examplelist.insert(ilist[i][0] + i, ilist[i][1])
print(examplelist)
흠; 너무긴가요;;
let index = '';
let indexFunc = (str) => {
index += str.charAt(0);
for(let i = 1; i < str.length; i++){
if(str.charAt(i)%2 == 0 && str.charAt(i-1)%2 == 0){
index += '*';
}else if(str.charAt(i)%2 == 1 && str.charAt(i-1)%2 == 1){
index += '-';
}
index += str.charAt(i);
}
return index;
}
console.log(indexFunc('565446488'));
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("숫자를 입력하세요 : ");
String num = sc.nextLine();//문자열로 받음
char[] numC = num.toCharArray();//캐릭터배열로 변환
for(int i=1;i<numC.length;i++){
System.out.print(numC[i-1]);
if(numC[i-1]%2==0){
if(numC[i]%2==0)
System.out.print("*");
}else{
if(numC[i]%2!=0)
System.out.print("-");
}
}//조건식 작성 홀수의 문자형의 아스키코드도 어차피 홀수이다. 굳이 인트형으로 변환할 필요없다.
System.out.println(numC[numC.length-1]);
sc.close();
}
var dashInsert = n => ("" + n).replace(/([13579]{2,})|([24680]{2,})/g, (_, o, e) => _.split("").join(o && "-" || e && "*"));
console.log(dashInsert(4546793));
Python 3로 풀었습니다. 깔끔하게 잘 안되네요.
def dash_insert(s):
def is_even(num):
return num is not None and num != 0 and num % 2 == 0
def is_odd(num):
return num is not None and num != 0 and num % 2 != 0
new = []
for c in s:
prev = int(new[-1]) if new else None
curr = int(c)
if is_even(curr) and is_even(prev):
new.append('*')
if is_odd(curr) and is_odd(prev):
new.append('-')
new.append(c)
return ''.join(new)
파이썬 3.5x입니다.
#120. Dash insert
def DI(n):
result = ''
for i in range(len(str(n))-1):
if (int(str(n)[i])%2) == (int(str(n)[i+1])%2) and int(str(n)[i])%2 ==0: #짝수가 이어서 나오는 경우
result = result + str(n)[i] + '*'
elif (int(str(n)[i])%2) == (int(str(n)[i+1])%2) and int(str(n)[i])%2 ==1: #홀수가 이어서 나오는 경우
result = result + str(n)[i] + '-'
else:
result = result + str(n)[i]
result = result + str(n)[len(str(n))-1]
return result
파이썬3
한 줄에 끝내려고 하다 보니 약간 복잡해졌네요
a = input('INPUT!! : ')
print(''.join([ x if (int(x) + int(y)) % 2 != 0 else(x + '-' if int(x) % 2 !=0 else x + '*') for x, y in zip(a, a[1:]) ]) + a[-1])
import java.util.*;
public class DashInsert {
public static String dashInsert(String str) {
int before, now;
StringBuffer result = new StringBuffer();
result.append(str.charAt(0));
before = Character.getNumericValue(str.charAt(0));
for(int i=1; i<str.length(); i++)
{
now = Character.getNumericValue(str.charAt(i));
if(now%2 == 0 && before%2 == 0)
result.append("*" + str.charAt(i));
else if(now%2 == 1 && before%2 == 1)
result.append("-" + str.charAt(i));
else
result.append(str.charAt(i));
before = now;
}
return result.toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println(dashInsert(str));
}
}
def DashInsert(numstr):
even, odd = lambda x:x%2==0, lambda x:x%2==1
lst = [int(c) for c in numstr]
dashed = numstr[0]
for p, c in zip(lst, lst[1:]):
dashed += '*'*(even(p) and even(c)) + '-'*(odd(p) and odd(c)) + str(c)
return dashed
print(DashInsert("4546793")) # "454*67-9-3"
def f(n):
m = ''
for i, chr1 in enumerate(n):
if i:
if int(chr1)%2 == 0 and int(n[i-1])%2 == 0:
m += '*'
elif int(chr1)%2 == 1 and int(n[i-1])%2 == 1:
m += '-'
m += chr1
print(m)
f('4546793')
public static void main(String[] args) {
String str = "4546793";
String result = "";
for(int i = 0; i < str.length(); i++) {
int mod = Integer.parseInt(String.valueOf(str.charAt(i))) % 2;
if(i > 0) {
int temp = Integer.parseInt(String.valueOf(str.charAt(i - 1))) % 2;
if(mod == temp) {
if(mod == 1) {
result += "-";
}
if(mod == 0) {
result += "*";
}
}
}
result += String.valueOf(str.charAt(i));
}
System.out.println(result);
}
# python 3.6
def DashInsert(inp):
"""inp: number in string type"""
rst = inp[0]
vl = int(rst)
for i in range(1, len(inp)):
vr = int(inp[i])
if vl % 2 == 0 and vr % 2 == 0:
rst += "*"
if vl % 2 == 1 and vr % 2 == 1:
rst += "-"
rst += str(vr)
vl = vr
return rst
print(DashInsert(input()))
import re
inp = "4546793334444"
res = re.sub('([02468]{2,})|([13579]{2,})', lambda x : '*'.join(x.group(1)) if x.group(1) else '-'.join(x.group(2)), inp)
print(res)
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine().trim();
System.out.print(s.charAt(0)); //첫번째 수는 그냥 출력
for (int i = 1; i < s.length(); i++) {
int before = s.charAt(i - 1) - '0';
int now = s.charAt(i) - '0';
boolean chk = Math.abs(before - now) % 2 == 0; //전수와 지금수 차가 2의 배수인가?
if (chk) { //두수의 차가 2의 배수는 *, - 중 하나다
if (now % 2 == 0) {
System.out.print("*" + now);
} else {
System.out.print("-" + now);
}
} else {
System.out.print(now);
}
}
}
}
python 2.7
리스트로 풀어서 했는데 다른 분들을 보니 홀수 짝수는 %2로 하는것이 훨씬 효울적일 듯 합니다.
def dash_insert(x):
odds = range(1,10,2)
evens = range(0,10,2)
x_lst = []
for char in x:
x_lst.append(int(char))
compare = zip(x_lst[:-1], x_lst[1:])
for j in range(len(compare)):
if compare[j][0] in odds and compare[j][1] in odds:
x_lst[j] = x[j] + '-'
elif compare[j][0] in evens and compare[j][1] in evens:
x_lst[j] = x[j] + '*'
x_lst = [str(x) for x in x_lst]
x_dashed = "".join(x_lst)
return x_dashed
print (dash_insert("4546793"))
python
def DashInsert(number, ans = ''):
for i in number:
if ans != '':
if eval("%".join(ans[-1]+'2')) == 0:
if eval("%".join(i+'2')) == 0: ans += '*'
else:
if eval("%".join(i+'2')) != 0: ans += '-'
ans += i
return ans
print(DashInsert('4546793'))
def dashinsert(n):
tmp=list(n)
for i in range(len(tmp)-1):
x,y=int(tmp[i]),int(tmp[i+1])
if x%2 and y%2:
tmp[i]+='-'
elif not x%2 and not y%2:
tmp[i]+='*'
return(''.join(tmp))
num='0'
while not num.isdigit() or int(num)<1:
num=(input('1 이상의 자연수: '))
print(dashinsert(num))
파이썬 3.6
def dashinsert(x):
convert =''
for i in range(1,len(x)+1):
if int(i) == len(x):
convert += x[i-1]
break
elif (int(x[i-1])%2) == 1 and (int(x[i])%2) == 1:
convert += x[i-1] + '-'
elif (int(x[i-1])%2) == 0 and (int(x[i])%2) == 0:
convert += x[i-1] + '*'
else:
convert += x[i-1]
print("\n"'', convert)
string = input(" ▶ 숫자로 구성된 문자열을 입력하세요 : ")
if string.isdigit():
dashinsert(string)
else:
print("\n"," ※ 숫자로만 구성된 문자열을 입력해주세요.","\n")
*결과값
▶ 숫자로 구성된 문자열을 입력하세요 : 4546793
454*67-9-3
def isodd(num) :
if num % 2 == 0 :
return True
else :
return False
def insertDash(numString) :
numStringSplit = list(numString)
for i in range(len(numStringSplit)-1) :
if isodd(int(numStringSplit[i])) : # 짝수일 때
if isodd(int(numStringSplit[i+1])) :
numStringSplit[i] = numStringSplit[i] + "*"
else :
if not isodd(int(numStringSplit[i])) : # 홀수일 때
if not isodd(int(numStringSplit[i+1])) :
numStringSplit[i] = numStringSplit[i] + "-"
return "".join(numStringSplit)
numString = input("Enter a string of numbers : ")
print(insertDash(numString))
a = input("숫자로된 문자열 입력 : ")
def dashin(str):
b = str
c = list(b)
d = ''
for i in range(len(b)-1):
if int(b[i])%2 ==0 and int(b[i+1])%2 ==0:
c[i] = b[i]+'*'
elif int(b[i])%2 == 1 and int(b[i+1])%2 ==1:
c[i] = b[i]+'-'
for i in range(len(b)):
d += c[i]
return d
print(dashin(a))
def Dashinsert(s):
result=''
i=0
while i<len(s)-1:
result+=s[i]
if int(s[i])%2==int(s[i+1])%2==0:result+='*'
if int(s[i])%2==int(s[i+1])%2==1:result+='-'
i+=1
print(result+s[-1])
def dash():
a=[]
num=""
n=input('number:')
for i in (str(n)):
a.append(i)
a=[int(x) for x in a]
for j in range(len(a)-1):
num=num+str(a[j])
if a[j]%2==1 and a[j+1]%2==1:
num=num+('-')
elif a[j]%2==0 and a[j+1]%2==0:
num=num+('*')
num=num+str(a[len(a)-1])
print num
num_str=input("숫자로 된 문자열을 입력하세요\n")
len_num_str=len(num_str)
ans_str=''
for k in range(len_num_str-1):
if (eval(num_str[k]+'+'+num_str[k+1]))%2==0:
if int(num_str[k])%2==0:
ans_str+=num_str[k]+"*"
else:
ans_str+=num_str[k]+"-"
else:
ans_str+=num_str[k]
ans_str+=num_str[-1]
print(ans_str)
파이썬으로 작성했습니다. 재귀함수를 이용해서 작성해보았습니다.
def dash_insert(s):
if len(s)<2:
return s
elif int(s[0])%2==0 and int(s[1])%2==0:
return s[0]+'*'+dash_insert(s[1:])
elif int(s[0])%2!=0 and int(s[1])%2!=0:
return s[0]+'-'+dash_insert(s[1:])
else:
return s[0]+dash_insert(s[1:])
dash_insert('4546793')
public class numberStream {
String str = new String("");
StringBuffer sb = new StringBuffer();
public numberStream(String str) {
this.str = str;
}
public StringBuffer numberMake() {
int numberFirst;
int numberSecond;
for(int i = 0; i < str.length() - 1; i++) {
boolean numberFirstEven = false;
boolean numberSecondEven = false;
numberFirst = Integer.parseInt(str.charAt(i) + "");
numberSecond = Integer.parseInt(str.charAt(i+1) + "");
if( numberFirst % 2 == 0 ) {
numberFirstEven = true;
}
if (numberSecond % 2 == 0) {
numberSecondEven = true;
}
if (numberFirstEven && numberSecondEven) {
sb.append(numberFirst).append('*');
} else if(!numberFirstEven && !numberSecondEven) {
sb.append(numberFirst).append('-');
} else {
sb.append(numberFirst);
}
}
sb.append(Integer.parseInt(str.charAt(str.length() - 1) + ""));
return sb;
}
}
def dashinsert():
put = input('input a number\n')
result = ''
remainder = -1
for charac in str(put):
if int(charac)%2 == remainder:
if remainder == 0: result = result + '*'
else: result = result + '-'
else: remainder = int(charac)%2
result = result + charac
return result
print(dashinsert())
Python 3이고 입력을 input함수로 구현했습니다
def dash_insert():
pass
numbers = input('data : ')
check = -1 # not 0, 1
for number in numbers:
number = int(number) # string -> int
if(0 == number % 2 and 0 == check): # check even number
print('*', end = "")
elif(1 == number % 2 and 1 == check): # check odd number
print('-', end = "")
print(number, end = "") # check -> print
check = number % 2 # before ( number % 2 )
print()
def main():
pass
dash_insert()
main()
import java.util.Scanner;
public class DashInsert{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int i,j;
System.out.println("숫자를 입력해주세요.");
long input = sc.nextLong();
String input1 = Long.toString(input);
int n = input1.length();
int [] a = new int[n];
for(i=0;i<n;i++){
a[i] = (int)(input%10);
input = (long)(input/10);
}
for(j=n-1;j>0;j--){
if(a[j]%2 == 1 && a[j-1]%2 == 1)
System.out.print(a[j] + "-");
else if(a[j]%2 == 0 && a[j-1]%2 == 0)
System.out.print(a[j] + "*");
else
System.out.print(a[j]);
}
System.out.println(a[0]);
}
}
inp = input()
tmp = inp.split()
arr = list(map(int, "".join(tmp)))
res = [str(arr[0])]
#res = []
for x in range(len(arr)-1):
#res.append(str(arr[x]))
if arr[x]%2==0 and arr[x+1]%2==0:
res.append('*')
if arr[x]%2==1 and arr[x+1]%2==1:
res.append('-')
res.append(str(arr[x+1]))
print("".join(res))
Swift입니다.
import Foundation
var separator = ["*", "-"]
func insertDash(_ input: String) -> String {
var result = ""
var number = Array(input)
for i in 0...(number.count - 2) {
result.append(number[i])
let r1 = Int(String(number[i]))! % 2
let r2 = Int(String(number[i + 1]))! % 2
if r1 == r2 {
result.append(separator[r1])
}
}
result.append(number[number.count - 1])
return result
}
if let input = readLine() {
print(insertDash(input))
}
파이썬 입니다.
import re
test_str = '45467935246134531234'
match = re.compile('[02468]{2,}|[13579]{2,}')
def replace_text(nums):
n_word = nums.group()
if int(n_word) % 2 == 0:
return '*'.join([x for x in n_word])
else:
return '-'.join([x for x in n_word])
r = match.sub(replace_text, test_str)
print(r)
package codingDojang;
import java.util.*;
public class InsertDash {
public String insertDash(String num) {
String result = "";
StringBuffer sb = new StringBuffer();
for(int i = 0;i<num.length()-1;i++) {
String dos = "";
int a = num.charAt(i);
int b = num.charAt(i+1);
if(a != b) {
result = sb.append(num.charAt(i)).toString();
continue;
} else {
dos = (a == 1) ? "-":"*";
result = sb.append(num.charAt(i) + dos).toString();
}
}
result = result + sb.append(num.charAt(num.length()-1)).toString();
return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
InsertDash id = new InsertDash();
System.out.println("숫자를 입력해주세요.");
String num = sc.nextLine();
System.out.println("결과값이 출력됩니다.");
System.out.print(id.insertDash(num));
}
}
def dash():
q=list(map(int,''.join(input("Input: "))))
print(q)
a=list(str(q[0]))
print(a)
for i in range(len(q)-1):
if q[i]%2==0 and q[i+1]%2==0:
a.append("*")
elif q[i]%2 != 0 and q[i+1]%2 !=0:
a.append("-")
a.append(str(q[i+1]))
print(a)
print(''.join(a))
function DashInsert(num){
var array = num.split("");
var result = array[0];
var checkNum = array[0];
for(var i = 1; i < array.length; i++){
if(array[i]%2 == 0 && checkNum%2 == 0){
result += "*";
}
else if(array[i]%2 == 1 && checkNum%2 == 1){
result += "-";
}
result += array[i];
checkNum = array[i];
}
return result;
}
재귀적으로 풀었습니다. 이전의 정수가 짝수였는지만 보고 계산합니다.
def dashInsert(str:String):String = {
def loop(s:String, preEven: Boolean):String = {
s match {
case x if s.isEmpty => ""
case x if (s.head.toInt - 48) % 2 == 1 =>{
if(preEven){
s.head + loop(s.tail, false)
} else {
"-" + s.head + loop(s.tail, false)
}
}
case x if (s.head.toInt - 48) % 2 == 0 =>{
if(preEven){
"*" + s.head + loop(s.tail, true)
} else {
s.head + loop(s.tail, true)
}
}
}
}
str.head + loop(str.tail, (str.head.toInt - 48) % 2 == 0)
}
println(dashInsert("4546793"))
import java.util.function.UnaryOperator;
public class DashInsert {
public static UnaryOperator<Integer> oddOrEven = i -> i % 2 == 0 ? 1:-1;
public static UnaryOperator<String> dashInsert = s -> {
int beforeState = 0;
int currentState = 0;
String result = "";
for (int i = 0; i < s.length(); i++) {
currentState = oddOrEven.apply(Character.getNumericValue(s.charAt(i)));
if (currentState == beforeState) {
if (currentState == 1) {
result += "*";
} else {
result += "-";
}
}
beforeState = currentState;
result += Character.toString(s.charAt(i));
}
return result;
};
public static void main(String[] args) {
System.out.println(dashInsert.apply("112234566778"));
}
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String word = br.readLine();
StringBuffer sb = new StringBuffer(word);
int cnt = 0;
for (int i=0, j=1; i<word.length()-1; i++, j++) {
int a = Integer.parseInt(word.charAt(i)+"");
int b = Integer.parseInt(word.charAt(j)+"");
if (a % 2 == 0 && b % 2 == 0) {
sb.insert(j+cnt, "*");
cnt++;
}
else if (a % 2 == 1 && b % 2 == 1) {
sb.insert(j+cnt, "-");
cnt++;
}
}
System.out.println(sb);
} // 자바
파이썬 3.6
def dashinsert(number):
def is_odd(a, b):
return int(a) % 2 != 0 and int(b) % 2 != 0
def is_even(a, b):
return int(a) % 2 == 0 and int(b) % 2 == 0
char = str(number)
result = char[0]
for i in range(0, len(char)-1):
if is_odd(char[i], char[i+1]):
result += '-'+char[i+1]
elif is_even(char[i], char[i+1]):
result += '*'+char[i+1]
else:
result += char[i+1]
print(result)
dashinsert(238901203123021300010)
2389012*03-1230*21-30*0*010
def DashInsert(str1): # 내 풀이
str1 = list(map(int, str1))
str2 = []
for i in range(len(str1)-1):
str2.append(str(str1[i]))
if str1[i] % 2 == 1 and str1[i + 1] % 2 == 1:
str2.append('-')
if str1[i] % 2 == 0 and str1[i+1]%2 == 0:
str2.append('*')
str2.append(str(str1[-1]))
return "".join(str2)
import re # 파이썬 선배님들의 정규표현식을 공부하면서 작성한 내용
def DashInsert(str1):
return re.sub("([1,3,5,7,9]{2,})|([2,4,6,8]{2,})",lambda x: "-".join(x.group(1)) if x.group(1) else "*".join(x.group(2)) ,str1)
print(DashInsert("4546793"))
Python
ans = ""
test = "4546793" #test = input()
for i in range(len(test)-1):
a, b = map(int, test[i:i+2])
if a%2 == 0 and b%2 == 0:
ans += str(a)+"*"
elif a%2 == 1 and b%2 == 1:
ans += str(a)+"-"
else:
ans += str(a)
ans += test[-1]
print(ans)
input_num = input("숫자를 입력해주세요")
output_num = []
for i in range(len(input_num)-1):
if int(input_num[i]) %2 == 1 and int(input_num[i+1]) %2 == 1:
output_num.append(input_num[i])
output_num.append("-")
elif int(input_num[i]) %2 == 0 and int(input_num[i+1]) %2 == 0:
output_num.append(input_num[i])
output_num.append("*")
else:
output_num.append(input_num[i])
output_num.append(input_num[len(input_num)-1])
print(''.join(str(x) for x in output_num))
def DashInsert(str):
input_num = list(str)
for index, letter in enumerate(input_num):
if index == len(input_num)-1: # 마지막 문자에 도달하면 검사 종료
break
if not letter.isnumeric(): # 기호라면 pass
continue
if int(input_num[index]) % 2 == 0: # 연속된 짝수라면
if int(input_num[index+1]) % 2 == 0:
input_num.insert(index+1, '*')
if int(input_num[index]) % 2 != 0: # 연속된 홀수라면
if int(input_num[index + 1]) % 2 != 0:
input_num.insert(index + 1, '-')
return input_num
input_num = input("문자열을 입력하세요 : ")
result = DashInsert(input_num)
space = ""
convert = space.join(result) # 리스트를 문자열로 변환
print(convert)
num = "4546793"
def DashInsert(n):
result = ''
for i in range(1,len(n)):
if int(n[i-1])%2 and int(n[i])%2: result += n[i-1]+'-'
elif not(int(n[i-1])%2 or int(n[i])%2): result += n[i-1]+'*'
else: result += n[i-1]
return result + n[i]
print(DashInsert(num))
# 454*67-9-3
import java.util.Scanner;
public class DashInsert {
public static void main(String[] args) {
String n = new Scanner(System.in).nextLine();
int temp = 0;
for (int i = 0; i < n.length(); i++) {
n = Integer.valueOf(n.substring(i, i + 1)) % 2 == 0
? temp == 2 ? n.substring(0, i) + "*" + n.substring(i++) : n
: temp == 1 ? n.substring(0, i) + "-" + n.substring(i++) : n;
temp = Integer.valueOf(n.substring(i, i + 1)) % 2 == 0 ? 2 : 1;
}
System.out.println(n);
}
}
package com.company;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.lang.*;
public class Main {
public static void main(String[] args) {
getAnswer();
}
public static void getAnswer(){
Scanner sc = new Scanner(System.in);
String num = sc.next();
List<Character> arr = new ArrayList<>();
int count = (num.charAt(0) - 48) % 2;
arr.add(num.charAt(0));
for (int i = 1; i < num.length(); i++){
int c = (num.charAt(i) - 48) % 2;
if(count == c) // 같으면
{
if(c == 0) // 짝수면
{
arr.add('*');
arr.add(num.charAt(i));
}
else // 홀수면
{
arr.add('-');
arr.add(num.charAt(i));
}
}
else // 다르면
{
count = c;
arr.add(num.charAt(i));
}
}
String st = "";
for(char a : arr)
{
st += Character.toString(a);
}
System.out.println(st);
}
}
파이썬입니다. 부호가 들어갈 곳을 따로 리스트에 저장해서 마지막에 넣어야할 곳에 넣는 방식입니다.
def DashInsert(string):
s = [int(x) for x in string]
temp = ["" for x in range(len(string)-1)]
answer = ""
for i in range(len(s)-1):
if s[i] % 2 == 0 and s[i+1] % 2 == 0 : temp[i] = "*"
elif s[i] % 2 != 0 and s[i+1] %2 != 0 : temp[i] = "-"
for i in range(len(s)) :
answer += str(s[i])
if len(temp) > i : answer += temp[i]
print(answer)
def dashInsert(data):
result=''
for i in range(1,len(data)):
result += data[i-1]
if int(data[i])%2 ==0 and int(data[i-1])%2 ==0:
result += "*"
elif int(data[i])%2 ==1 and int(data[i-1])%2 ==1:
result += "-"
result+=data[i]
print(result)
data = "4546793"
dashInsert(data)
class Program
{
static void Main(string[] args)
{
string strInput = string.Empty;
char[] token = Console.ReadLine().ToCharArray();
for (int i = 0; i < token.Length; i++)
{
if (i == 0)
{
strInput = String.Format("{0}", token[i]);
}
else if (token[i-1] % 2 == 0 && token[i] % 2 == 0)
{
strInput += String.Format("*{0}", token[i]);
}
else if (token[i-1] % 2 != 0 && token[i] % 2 != 0)
{
strInput += String.Format("-{0}", token[i]);
}
else if (token[i-1] % 2 == 0 && token[i] % 2 != 0)
{
strInput += String.Format("{0}", token[i]);
}
else
strInput += String.Format("{0}", token[i]);
}
Console.WriteLine(strInput);
}
}
a=input()
lst=[]
for x in range(len(a)):
lst.append(a[x])
if x==len(a)-1:
break
elif int(a[x])%2==0 and int(a[x+1])%2==0:
lst.append('*')
elif int(a[x])%2!=0 and int(a[x+1])%2!=0:
lst.append('-')
print(''.join(lst))
// ===============================
int[] n = { 4, 5, 4, 6, 7, 9, 3 };
String temp = n[0] + "";
for (int i = 0; i < n.length - 1; i++) {
boolean a = n[i] % 2 == 0;
boolean b = (n[i + 1]) % 2 == 0;
if (a && b) {
temp += "*";
} else if (!a && !b) {
temp += "-";
}
temp += n[i + 1];
}
System.out.println(temp);
def DashInsert(input):
output = ''
last = -1
for ch in input:
current = int(ch)%2
if current == last:
if last == 0: #even
output += '*'
else:
output += '-'
last = current
output += ch
print(output)
DashInsert(input())
num=input("숫자입력:")
num2=int(num)
numlist=[]
result=""
numlist.append(num[0])
for i in range(0,len(num)-1,1):
if int(num[i])%2==0 and int(num[i+1])%2==0 :
num3=str(num2)
plus="+"+num3[i+1]
numlist.append(plus)
elif int(num[i])%2!=0 and int(num[i+1])%2!=0 :
num3=str(num2)
plus="*"+num3[i+1]
numlist.append(plus)
else :
numlist.append(num[i+1])
for i in numlist:
result+=i
print(result)
def dash_insert(a):
result =""
for i in range (1, len(a)) :
#연속 짝수인 경우
if(int(a[i-1])%2==0 and int(a[i])%2==0) :
result += a[i-1]+"*"
#연속 홀수인 경우
elif(int(a[i-1])%2!=0 and int(a[i])%2!=0) :
result += a[i-1]+"-"
else :
result += a[i-1]
#마지막 숫자
result+=a[len(a)-1]
print (result)
q = input()
fz = q[0:-1]
sz = q[1:]
cal = zip(fz, sz)
result = ''
for f, s in cal:
if abs(int(f) - int(s)) % 2 == 0:
if int(f) % 2 != 0: #홀수
result += f + '-'
else:
result += f + '*'
else:
result += f
result += sz[-1]
print(result)
int main()
{
char arr1[2] = { '+', '*' };
char arr2[1000];
int num;
scanf("%d", &num);
scanf("%s", arr2);
for (int i = 0; i < num; i++)
{
if (((arr2[i] - '0') % 2 == 0) && ((arr2[i + 1] - '0') % 2 == 0))
{
if (arr2[i + 1] != NULL)
{
printf("%c%c", arr2[i], arr1[1]);
}
else
printf("%c", arr2[i]);
}
else if (((arr2[i] - '0') % 2 != 0) && ((arr2[i + 1] - '0') % 2 != 0))
{
printf("%c%c", arr2[i], arr1[0]);
}
else
printf("%c", arr2[i]);
}
return 0;
}
string = list(input("숫자 입력 : "))
for i in range(0, len(string)-1) :
if int(string[i]) % 2 == 0 and int(string[i+1]) % 2 == 0 : string[i] = (string[i] + '*')
elif int(string[i]) % 2 == 1 and int(string[i+1]) % 2 == 1 : string[i] = (string[i] + '-')
print(''.join(string))
def DashInsert(num):
stnum = str(num)
i=0
while True:
if stnum[i].isdigit():
N = int(stnum[i])
Nnext = int(stnum[i+1])
if N % 2 == 1 and Nnext % 2 == 1: stnum = stnum[0:i+1] + '-' + stnum[i+1:]
elif N % 2 == 0 and Nnext % 2 == 0: stnum = stnum[0:i+1] + '*' + stnum[i+1:]
else:
pass
i += 1
if i == len(stnum)-1: break
return stnum
print(DashInsert(4546793))
출력 : 454*67-9-3
ino = input()
str_input = list(ino)
str_output = []
for number, i in enumerate(str_input):
str_output.append(i)
while number != len(str_input) - 1:
if int(i) % 2 == 0 and int(str_input[number+1]) % 2 == 0:
str_output.append('*')
if int(i) % 2 == 1 and int(str_input[number+1]) % 2 == 1:
str_output.append('-')
break
print(''.join(str_output))
#include<stdio.h>
#include<string.h>
int main(void)
{
char a[50] = "";
int i, j;
scanf_s("%s", &a, 50);
int len = strlen(a);
for (i = 0; i < len; i++)
{
if (a[i] >= 48 && a[i] <= 57)
{
if ((a[i] - '0') % 2 == 0 && (a[i + 1] - '0') % 2 == 0)
{
for (j = len - 1; j >= i + 1; j--)
{
a[j + 1] = a[j];
}
a[i + 1] = '*';
len++;
}
else if ((a[i] - '0') % 2 == 1 && (a[i + 1] - '0') % 2 == 1)
{
for (j = len - 1; j >= i + 1; j--)
{
a[j + 1] = a[j];
}
a[i + 1] = '-';
len++;
}
}
}
for (int k = 0; k < len; k++)
{
printf("%c", a[k]);
}
return;
}
def DashInsert(n):
result = list()
for i in range(len(n)-1):
if int(n[i]) % 2 == 0 and int(n[i+1]) % 2 == 0:
result.append(n[i]+'*')
elif int(n[i]) % 2 != 0 and int(n[i+1]) % 2 != 0:
result.append(n[i]+'-')
else:
result.append(n[i])
result.append(n[len(n)-1])
return ''.join(result)
n = input()
print(DashInsert(n))
def Dash(st):
return st[0] + ''.join(('*' if (int(st[x])%2 + int(st[x-1])%2) == 0 else '-')+st[x] if eval(st[x]+'+'+st[x-1])%2 == 0 else st[x] for x in range(1,len(st)))
function DashInsert(str){
let origin = str.slice('')
let result = ''
for(let i = 0; i<origin.length; i++){
if(origin[i-1]%2 === 0 && origin[i]%2 === 0){
result +=('*'+ origin[i])
}else if(origin[i-1]%2 === 1 && origin[i]%2 === 1){
result +=('-'+origin[i])
}else{
result += (origin[i])
}
}
return result
}
DashInsert('4546793')
def DashInsert(a):
b = ''
for i in range(len(a)-1):
if int(a[i]) % 2 == 1 and int(a[i+1]) % 2 == 1:
b += a[i] + '-'
elif int(a[i]) % 2 == 0 and int(a[i+1]) % 2 == 0:
b += a[i] + '*'
else:
b += a[i]
b += a[len(a)-1]
return b
print(DashInsert('4546793'))
python입니다.
def dashInsert(strNum):
listNum = list(strNum)
result = ''
for i, name in enumerate(listNum):
result += name
if i + 1 != len(listNum):
if int(name) % 2 == 0:
if int(listNum[i+1]) % 2 == 0:
result += "*"
else:
if int(listNum[i+1]) % 2 != 0:
result += "-"
return result
print(dashInsert('4546793'))
namespace codingdojang_test
{
class Program
{
static void Main(string[] args)
{
int input = int.Parse(Console.ReadLine());
List<string> input_list = new List<string> { };
while (input > 0)
{
input_list.Add((input % 10).ToString());
input /= 10;
}
int input_list_count = input_list.Count();
input_list.Reverse();
for (int i = 0; i < input_list_count; i++)
{
if (i + 1 < input_list_count)
{
if (int.Parse(input_list[i]) % 2 == 0 && int.Parse(input_list[i + 1]) % 2 == 0)
{
input_list.Insert(i + 1, "*");
input_list_count++;
i++;
}
else if (int.Parse(input_list[i]) % 2 == 1 && int.Parse(input_list[i + 1]) % 2 == 1)
{
input_list.Insert(i + 1, "-");
input_list_count++;
i++;
}
}
}
foreach (var e in input_list)
{
Console.Write(e);
}
Console.WriteLine("");
}
}
}
num_str = input('입력: ')
num_str_list=[]
ex_num=num_str[0]
num_str_list.append(ex_num)
for index_num in range(1,len(num_str)):
if int(ex_num)%2==0 and int(num_str[index_num])%2==0:
num_str_list.append('*')
num_str_list.append(num_str[index_num])
elif int(ex_num)%2==1 and int(num_str[index_num])%2==1:
num_str_list.append('-')
num_str_list.append(num_str[index_num])
else:
num_str_list.append(num_str[index_num])
ex_num = num_str[index_num]
print(''.join(num_str_list))
x = input()
for i in range(len(x)-1):
print (x[i], end='')
if int(x[i]) % 2 == 0 and int(x[i+1]) % 2== 0:
print('*',end='')
elif int(x[i]) % 2 != 0 and int(x[i+1]) % 2!= 0:
print('-',end='')
if i == len(x)-2:
print(x[i+1])
#마크다운 문법 설명 봐도 모르겠어요
package level1;
import java.util.Scanner;
public class DashInsert {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String result = scan.nextLine();
String total = "";
for(int i=0; i<=result.length()-1; i++){
char val = result.charAt(i);
char val_compare = i >= result.length()-1 ? 'y' : result.charAt(i+1);
if(val_compare == 'y'){
total += val+"";
break;
}
if(val%2 == 0 && val_compare%2 ==0){
total += val + "*";
i++;
}else if(val%2 != 0 && val_compare%2 !=0){
total += val + "-";
i++;
}else{
total += val+"";
}
}
System.out.println(total);
}
}
def DashInsert(str_num):
even_count = 0
odd_count = 0
for cha_num in str_num:
start = cha_num
if int(cha_num) % 2 == 1:
odd_count += 1
if even_count != 0:
even_count = 0
if odd_count >= 2:
cha_num = cha_num.replace(cha_num, "-"+cha_num)
elif int(cha_num) % 2 == 0:
even_count += 1
if odd_count != 0:
odd_count = 0
if even_count >= 2:
cha_num = cha_num.replace(cha_num, "*"+cha_num)
str_num = str_num.replace(start, cha_num)
return str_num
print(DashInsert('4546793'))
def dash_insert(numbers):
a = list(numbers)
print(a)
n = len(a)
result = []
for i in range(0, n - 1):
result.append(a[i])
if int(a[i]) % 2 == 1 and int(a[i + 1]) % 2 == 1:
result.append('-')
elif int(a[i]) % 2 == 0 and int(a[i + 1]) % 2 == 0:
result.append('*')
return ''.join(result)
user_input = input("Enter numbers: ")
print(dash_insert(user_input))
def Dash(S):
if len(S)==1:
return S
if (int(S[0])+int(S[1]))%2==1:
return S[0]+Dash(S[1:])
elif(int(S[0])+int(S[1]))%2==0:
if int(S[0])%2==1:
return S[0]+'-'+Dash(S[1:])
else:
return S[0]+'*'+Dash(S[1:])
s=input()
print(Dash(s))
다른 멋진 풀이도 많지만, 재귀에 익숙해질 겸 굳이 재귀함수를 이용하여 풀이하여보았읍니다. 너무 멍텅구리라 6시간이나 걸린건 안 비밀... 그래도 시간을 많이 들인만큼, 깨달은바도 많았던 좋은 문제였읍니다^^
def Dash_Insert(InStr):
In_Dash = []
for Idx, Val in enumerate(InStr):
if Idx < len(InStr)-1:
if int(InStr[Idx])%2 == 0 and int(InStr[Idx+1])%2 == 0:
In_Dash.append(Val)
In_Dash.append('*')
elif int(InStr[Idx])%2 != 0 and int(InStr[Idx+1])%2 != 0:
In_Dash.append(Val)
In_Dash.append('-')
else:
In_Dash.append(Val)
In_Dash.append(InStr[len(InStr)-1])
return(In_Dash)
In1 = input("숫자열을 입력하시오: ")
Re = Dash_Insert(In1)
print(''.join(Re))
python 3.6
def DashInsert(nstr):
result = nstr
i = 1
while i < len(nstr):
fst, snd = int(nstr[-i]), int(nstr[-(i+1)])
if fst * snd % 2 == 1:
result = result[:len(nstr)-i] + '-' + result[len(nstr)-i:]
elif (fst + snd) % 2 == 0:
result = result[:len(nstr)-i] + '*' + result[len(nstr)-i:]
i += 1
return result
user_input = input('input number (integer) : ')
print(DashInsert(user_input))
#파이썬 3.7
gulja=input("아무 숫자나 쳐보세요")
result=gulja[0]
for i in range(1,len(gulja)):
if int(gulja[i]) % 2 == 0 and int(gulja[i-1]) % 2 == 0:
result=result+"*"
if int(gulja[i]) % 2 ==1 and int(gulja[i-1]) % 2 == 1:
result=result+"-"
result=result+gulja[i]
print(result)
data = list(map(int, input()))
result = []
for i, j in enumerate(data):
result.append(str(j))
if i < len(data) - 1:
odd = j % 2 == 1
next_odd = data[i+1] % 2 == 1
if odd and next_odd:
result.append('-')
elif not odd and not next_odd:
result.append('*')
print(''.join(result))
var DashInsert = function(str) {
// 연속된 숫자 홀수일때 사이에 '-'를 추가하세요
// 연속된 짝수면 * 홀수면 -
let result = '';
for(let i=0; i<str.length; i++){
if(str[i] % 2 && str[i+1] % 2){
result += str[i] + '-';
}else if(str[i] % 2 === 0 && str[i+1] % 2 === 0){
result += str[i] + '*';
}else{
result += str[i]
}
}
return result;
}
DashInsert('4546793')
//454*67-9-3;
def DashInsert(text):
t = []; result = []
for i in range(len(text)):
t.append(int(text[i]))
result.append(t[0])
for i in range(1,len(t)):
if t[i-1]%2 == 0 and t[i]%2 == 0:
result.append("*")
result.append(t[i])
elif t[i-1]%2 == 1 and t[i]%2 == 1:
result.append("-")
result.append(t[i])
else:
result.append(t[i])
answer = ''
for i in range(len(result)):
answer += str(result[i])
return answer
print(DashInsert("4546793"))
n=list(input("숫자로 구성된 문자열 출력: "))
i=0
result=""
while i<=len(n)-2:
if n[i]=='*' or n[i]=='-':
pass
elif int(n[i])%2==0 and int(n[i+1])%2==0:
n.insert(i+1,'*')
elif int(n[i])%2==1 and int(n[i+1])%2==1:
n.insert(i+1,'-')
i+=1
for i in n:
result=result+i
print("\"{0}\"".format(result))
python
num_word = str(input('임의의 숫자열을 입력하세요> '))
def DashInsert(num_word):
word_list = list(str(num_word))
result = []
for i in range(0,len(word_list)-1):
if int(word_list[i]) % 2 == 1 and int(word_list[i+1]) % 2 == 1:
result.append(word_list[i])
result.append('-')
elif int(word_list[i]) % 2 == 0 and int(word_list[i+1]) % 2 == 0:
result.append(word_list[i])
result.append('*')
else:
result.append(word_list[i])
result.append(word_list[len(word_list)-1])
answer = ''.join(w for w in result)
return answer
DashInsert(num_word)
Python 3.7
a = input()
ev = ("0", "2", "4", "6", "8")
od = ("1", "3", "5", "7", "9")
i = 1
while i < len(a):
if a[i-1] in ev and a[i] in ev:
a = a[:i]+"*"+a[i:]
i += 2
elif a[i-1] in od and a[i] in od:
a = a[:i]+"-"+a[i:]
i += 2
else:
i += 1
print(a)
def DashInsert(num_str):
a = []
map_1 = list(map(int, num_str))
for i in range(len(num_str)-1):
a.append(str(map_1[i]))
if map_1[i] % 2 == 0 and map_1[i+1] % 2 == 0:
a.append('*')
elif map_1[i] % 2 == 1 and map_1[i+1] % 2 == 1:
a.append('-')
a.append(str(map_1[-1]))
return ''.join(a)
num_str = input()
print(DashInsert(num_str))
boolean flag = false;
int m=0, n=0;
StringBuffer sb = new StringBuffer();
System.out.print(">> 숫자로 된 문자열을 입력하시오 : ");
String input = sc.nextLine();
char[] j = String.valueOf(input).toCharArray();
for(int k=0; k<j.length; k++) {
String s = "";
if(k<j.length-1) {
m = Character.getNumericValue(j[k]);
n = Character.getNumericValue(j[k+1]);
if(m%2!=0 && n%2!=0) {//m이 홀수+n이 홀수
s = "-";
}
else if(m%2==0 && n%2==0) {//m이짝수+n이짝수
s = "*";
}
}
else {
m = Character.getNumericValue(j[k]);
s = "";
}
sb.append (String.valueOf(m)+s);
}
System.out.println(sb.toString());
샘플 input : 숫자로 된 문자열을 입력하시오 : 12255578787444 결과 : 1225-5-5-7878744*4
n = int(input("숫자를 입력 하세요 : "))
list_n=list(str(n))
result = []
for i in range(len(list_n)-1):
if int(list_n[i])%2 ==0 and int(list_n[i+1])%2 == 0:
result.append(list_n[i]+"*")
elif int(list_n[i])%2 == 1 and int(list_n[i+1])%2 == 1:
result.append(list_n[i]+"-")
else :
result.append(list_n[i])
print("".join(result)+list_n[len(list_n)-1])
s = input("Input string number: ")
result = s[0]
for i in range(1, len(s)):
if int(s[i]) % 2 == 1 and int(s[i-1]) % 2 == 1:
result = result + "-" + s[i]
elif int(s[i]) % 2 == 0 and int(s[i-1]) % 2 == 0:
result = result + "*" + s[i]
else:
result += s[i]
print(result)
package d120_DashInsert;
import java.util.Scanner;
public class DashInsert {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
boolean odd=false, even=false;
String input = sc.next();
String output="";
for(int i=0; i<input.length(); i++) {
if((int)input.charAt(i)%2==1) { //odd, 즉 홀수인 경우
if(odd==true) output+="-"; //이전 숫자도 홀수였던 경우
else { //이전 숫자가 홀수가 아니었던 경우
odd=true;
even=false;
}
}
else { //even, 즉 짝수인 경우
if(even==true) output+="*"; //이전 숫자도 짝수였던 경우
else { // 이전 숫자가 짝수가 아니었던 경우
even=true;
odd=false;
}
}
output+=input.charAt(i); //숫자 넣기
}
System.out.println(output);
}
}
package practiceLv1;
import java.util.*;
public class DashInsert {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String 입력 = scan.nextLine();
String[] 입력배열 = 입력.split("");
List<String> numbers = new ArrayList<String>();
for(int j = 0; j<입력배열.length; j++) {
numbers.add(입력배열[j]);
}
int[] 입력배열인트 = Arrays.stream(입력배열).mapToInt(Integer::parseInt).toArray();
for(int i=0; i<입력배열인트.length-1; i++) {
if(입력배열인트[i+1]!=0) {
if(입력배열인트[i]%2==0&&입력배열인트[i+1]%2==0) {
numbers.set(i, 입력배열[i]+"*");
}
if(입력배열인트[i]%2==1&&입력배열인트[i+1]%2==1) {
numbers.set(i, 입력배열[i]+"-");
}
}}
입력배열 = numbers.toArray(입력배열);
String 완성 = String.join("", 입력배열);
System.out.println(완성);
}
}
파이썬 입니다.
string=str(input('정수를 입력하세요. : '))
attatch=string[0]
for i in string: # string 같은경우 속성이 str()이므로 이미 문자열 자체에 인덱스가 있고 '1234' 문자열은
if int(attatch[-1])%2==0 and int(i)%2==0: # 순서대로 1, 2, 3, 4가 for문에 의해 나오게 된다.
attatch += '*'+ i # attatch = attatch + '*'+ i
elif int(attatch[-1])%2==1 and int(i)%2==1: # attatch와 i 는 이미 str() 속성이므로 int()붙여 계산이 가능하도록함.
attatch += '-'+ i # attatch = attatch + '-'+ i
else:
attatch += i # attatch = attatch + i
print( attatch[2:] ) # attatch=string[0] 으로 맨 앞에 이미 첫숫자를 붙인상태에서 똑같은 숫자를 for문에서 string에서
# 가져와 붙이므로 앞에 두 숫자는 홀수든 짝수든 같은 숫자이므로 숫자+('*'or'-')가 붙으므로
# 앞에 두 문자를 슬라이싱하여 출력하면 처음 입력했던 string이 그대로 출력되게 된다.
# 되도록 슬라이싱은 안하고 싶었지만 도저히 앞부분에서 논리를 어떻게 적용해야할지 몰라
# 궁여지책으로 슬라이싱을 붙이긴했지만 좀 더 나은 방법을 알고 계신분은 댓글로 남겨주세요.
user_input = input('숫자를 입력하세요 : ')
# sample_input = '4546793'
def dash_insert(num_list):
ans_list = list(num_list)
for num in num_list[1:]:
if int(num) % 2 == 0 \
and int(list(num_list)[list(num_list).index(num) - 1]) % 2 == 0:
ans_list.insert(ans_list.index(num), '*')
elif int(num) % 2 == 1 \
and int(list(num_list)[list(num_list).index(num) - 1]) % 2 == 1:
ans_list.insert(ans_list.index(num), '-')
print(ans_list)
dash_insert(user_input)
파이선3.6
DashInsert_var = list(str(input()))
new_var = [str(DashInsert_var[0])]
#
for i in range(len(DashInsert_var)-1):
if int(DashInsert_var[i]) % 2 == int(DashInsert_var[i+1]) % 2 == 0 :
new_var.append("*")
elif int(DashInsert_var[i]) % 2 == int(DashInsert_var[i+1]) % 2 != 0 :
new_var.append("-")
new_var.append(str(DashInsert_var[i+1]))
print(''.join(new_var))
파이썬입니다.
b = list(map(int,' '.join(str(int(input('숫자를 입력하세요.')))).split()))
answer = [str(b[0])]
for i in range(len(b)-1):
if b[i] % 2 == 0 and b[i+1] % 2 == 0:
answer.append('*')
elif b[i] % 2 == 1 and b[i+1] % 2 == 1:
answer.append('-')
answer.append(str(b[i+1]))
print(''.join(answer))
왕초보 입니다. ㅜㅡㅜ
num_in = list(input("숫자를 입력하세요"))
result = []
try :
for i in range(len(num_in)):
a = num_in[i]
b = num_in[i+1]
if int(a) % 2 == int(b) % 2:
if int(a) % 2 == 0:
result.append(a)
result.append('*')
elif int(a) % 2 == 1:
result.append(a)
result.append('-')
else :
result.append(a)
except IndexError :
result.append(a)
result2 = "".join(result)
print(result2)
m = input("입력: ")
n = list(m)
result =[]
for i in range(0, len(n)-1):
if int(n[i])%2 == 0 and int(n[i+1])%2 == 0:
result.append(n[i])
result.append('*')
elif int(n[i])%2 == 1 and int(n[i+1])%2 == 1:
result.append(n[i])
result.append('-')
else:
result.append(n[i])
result.append(n[len(n)-1])
print("".join(result))
n = input("Enter the Number:")
a = list(str(n))
b = []
b.append(a[0])
for i in range(0,len(a)-1):
if (int(a[i])%2) == 0 and (int(a[i+1])%2) == 0:
b.append('*'+a[i+1])
elif (int(a[i])%2) == 1 and (int(a[i+1])%2) == 1:
b.append('-'+a[i+1])
else:
b.append(a[i+1])
print(''.join(b))
N,Nlist,Nfinish,m = list(map(int,input())),list(),"",1
for i in range(len(N)):
try:
Nlist.append(N[i])
if N[i] % 2 == 0 and N[i+1] % 2 == 0:
Nlist.insert(i+m,'*')
m += 1
if N[i] % 2 ==1 and N[i+1] % 2 == 1:
Nlist.insert(i+m,'-')
m += 1
except IndexError:
break
print(Nlist)
data = "4546793"
numbers = list(map(int, data)) result = []
for i, num in enumerate(numbers): result.append(str(num)) if i < len(numbers)-1: is_odd = num%2 == 1 is_next_odd = numbers[i+1]%2 == 1 if is_odd and is_next_odd: result.append("-") elif not is_odd and not is_next_odd: result.append("*")
print("".join(result))
def Dashinsert(s):
lst = list(map(int,s))
i=0
while True:
if lst[i]%2==0 and lst[i+1]%2==0:
lst.insert(i+1,'*')
i+=2
if lst[i]%2==1 and lst[i+1]%2==1:
lst.insert(i+1,'-')
i+=2
else:
i+=1
if i==len(lst)-1:
break
lst= list(map(str, lst))
return ''.join(lst)
def dash_insert(x):
result = list(x)
for i in range(len(result)):
if i + 1 < len(result):
if int(result[i]) % 2 == 0 and int(result[i + 1]) % 2 == 0:
result[i] += '*'
elif int(result[i]) % 2 != 0 and int(result[i + 1]) % 2 != 0:
result[i] += '-'
return ''.join(result)
case = "4546793"
print(dash_insert(case))
def dashinsert(n):
i,nn=0,[]
nn.append(n[0])
while (i<len(n)-1):
if int(n[i])%2==0 and int(n[i+1])%2==0:
nn.append('*')
if int(n[i])%2==1 and int(n[i+1])%2==1:
nn.append('-')
nn.append(n[i+1])
i+=1
return(nn)
for i in dashinsert(str(input('Input number....'))):
print (i, end='')
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Q120 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String[] input = scan.next().split("");
ArrayList<String> num = new ArrayList<String>(Arrays.asList(input));
for (int i = 1; i < num.size(); i++) {
if (num.get(i)!="*" && num.get(i)!="-" && num.get(i - 1)!="*" && num.get(i - 1)!="-") {
if (Integer.parseInt(num.get(i))%2==0 && Integer.parseInt(num.get(i - 1))%2==0) {
num.add(i, "*");
} else if (Integer.parseInt(num.get(i))%2==1 && Integer.parseInt(num.get(i - 1))%2==1) {
num.add(i, "-");
}
}
}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < num.size(); i++)
sb.append(num.get(i));
System.out.println(sb.toString());
scan.close();
}
}
number = input ("numbers?")
temp = []
for i in range (0, len(number)-1):
if int(number[i]) % 2 == 0 and int(number[i+1]) % 2 == 0:
temp.append(number[i]+"*")
elif int(number[i]) % 2 == 1 and int(number[i+1]) % 2 == 1:
temp.append(number[i] + "-")
else:
temp.append(number[i])
print ("".join(temp) + number[len(number)-1])
print (temp)
def dash_insert(s):
def insert_func(i):
if int(s[i]) % 2 == 0 and int(s[i + 1]) % 2 == 0:
return "*"
elif int(s[i]) % 2 == 1 and int(s[i + 1]) % 2 == 1:
return "-"
else:
return ""
return "".join([s[i] + insert_func(i) for i in range(len(s) - 1)]) + s[-1]
a = str(input())
i=0
while i < (len(a)-1):
if a[i] == '*' or a[i] == '-':
i += 1
elif a[i+1] == '*' or a[i+1] == '-':
i += 1
elif int(a[i])%2==0 and int(a[i+1])%2==0:
a = a.replace(a[i:i+2], a[i]+'*'+a[i+1])
i += 1
elif int(a[i])%2==1 and int(a[i+1])%2==1:
a = a.replace(a[i:i+2], a[i]+'-'+a[i+1])
i += 1
else:
i += 1
print(a)
def DashInsert(n):
DashInsert_list=list(map(int,((":".join(n)).split(":"))))
answer=[]
n=len(DashInsert_list)
for i in range (0,n):
if i < (n - 1):
jjack = DashInsert_list[i] % 2 == 0 and DashInsert_list[i + 1] % 2 == 0
hol = DashInsert_list[i] % 2 != 0 and DashInsert_list[i + 1] % 2 != 0
if jjack:
answer.append(str(DashInsert_list[i]))
answer.append("*")
if hol:
answer.append(str(DashInsert_list[i]))
answer.append("-")
else:
answer.append(str(DashInsert_list[i]))
if i == (n - 1):
answer.append(str(DashInsert_list[i]))
k=""
for i in answer:
k+=i
return '"'+k+'"'
print(DashInsert("4546793"))
input_temp = input()
print(input_temp)
for i in range(0,len(input_temp)) :
print(input_temp[i],end='')
if i==len(input_temp)-1 :
break
if int(input_temp[i])%2==0 and int(input_temp[i+1])%2==0 :
print('*',end='')
elif int(input_temp[i])%2==1 and int(input_temp[i+1])%2==1 :
print('-',end='')
if 문을 반복하여 복잡하게 풀이하였지만, 그래도 해결했다는거에 위안을 가지네요 선배님들 정답보고 많이 배워가겠습니다
ps. input이 str으로 출력되고 그 출력값을 그냥 인덱싱하면 되는데 굳이 리스트로 변환해서 풀었네요.. 기초의 중요성을 새삼느끼는 이번 문제를 풀면서 기본적인걸 많이 배웠습니다. 좀 더 간추릴 수 있지만 일부러 수정 전 코드 남겨봐요
numbers = #str으로 출력
print(numbers)
int_li_num = list(map(int,list(numbers))) #불필요 문자열 인덱싱가능
for x in range(len(numbers)):
if x == len(numbers)-1:
print(int_li_num[x],end='')
break
elif (int_li_num[x] + int_li_num[x + 1]) % 2 == 0:
if int_li_num[x] % 2 == 0:
print(int_li_num[x],end=''),print('*',end="") #여기 부호에서 띄어쓰기됨
else:
print(int_li_num[x],end=''),print('-',end="")
else:
print(int_li_num[x],end="")
import java.util.ArrayList;
import java.util.Scanner;
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
ArrayList<String> num = new ArrayList<String>();
System.out.println("숫자를 입력하시오!");
String input = scan.nextLine();
String[] a = input.split("");
for(int i=0;i<a.length;i++)
{
num.add(a[i]);
} // Arraylist 받아서 생성!!
for(int k=0;k<num.size()-1;k++)
{
if((num.get(k)=="-") ||(num.get(k)=="*") )
{
continue; // 루프 끝으로 이동
}
else if((Integer.parseInt(num.get(k))%2 ==0) &&
(Integer.parseInt(num.get(k+1))%2 ==0 ))
{
num.add(k+1,"*");
}
else if((Integer.parseInt(num.get(k))%2 ==1) &&
(Integer.parseInt(num.get(k+1))%2 ==1 ))
{
num.add(k+1,"-");
}
}
for(String i : num)
{
System.out.print(i);
}
}
}
package test;
import java.util.*;
public class Test{
public static void main(String[] args) {
ArrayList<Character> arr = new ArrayList<>();
Scanner sc = new Scanner(System.in);
String input = sc.next();
sc.close();
for(int i =0;i<input.length(); i++) {
arr.add(input.charAt(i));
}
for(int j =0;j<arr.size()-1;j++) {
if((Character.getNumericValue(arr.get(j))%2==0) && (Character.getNumericValue(arr.get(j+1))%2==0))
arr.add(j+1,'*');
else if((Character.getNumericValue(arr.get(j))%2==1) && (Character.getNumericValue(arr.get(j+1))%2==1))
arr.add(j+1,'-');
}
System.out.println(arr);
}
}
namespace _58일차_9월24일
{
class MainApp
{
public List<string> DashInsert(string Input_Data)
{
char[] Data = Input_Data.ToCharArray();
List<string> result = new List<string>();
for (int i = 0; i < Data.Length; i++)
{
try
{
result.Add(Data[i].ToString());
if (int.Parse(Data[i].ToString()) % 2 == 0 && int.Parse(Data[i + 1].ToString()) % 2 == 0)
{
result.Add("*");
}
else if (int.Parse(Data[i].ToString()) % 2 == 1 && int.Parse(Data[i + 1].ToString()) % 2 == 1)
{
result.Add("-");
}
else continue;
}
catch (System.IndexOutOfRangeException)
{
continue;
}
}
return result;
}
static void Main(string[] args)
{
//(예, 454 => 454, 4546793 => 454*67-9-3)
Console.Write("Number Input : ");
string Input = Console.ReadLine();
MainApp a = new MainApp();
foreach (var result_1 in a.DashInsert(Input))
{
Console.Write(result_1);
}
}
}
}
n = input('num : ')
def DashInsert(n) :
n = list(n)
for i in range(len(n)-1) :
if int(n[i])%2 == 0 and int(n[i+1])%2 == 0 :
n[i] = n[i] + '*'
elif int(n[i])%2 == 1 and int(n[i+1])%2 == 1 :
n[i] = n[i] + '-'
n = ''.join(n)
return n
print(DashInsert(n))
자바입니다.
import java.util.ArrayList;
import java.util.Arrays;
public class Dash_Insert {
public static String DI(String num) {
String a[] = num.split("");
ArrayList<String> List = new ArrayList<String>();
for(int i =0; i<a.length;i++) {
if(i==a.length-1) {
List.add(a[i]);
break;
}
if(Integer.parseInt(a[i])%2==0 && (Integer.parseInt(a[i+1])%2==0)){
List.add(a[i]);
List.add("*");
}
else if(Integer.parseInt(a[i])%2==1 && (Integer.parseInt(a[i+1])%2==1)){
List.add(a[i]);
List.add("-");
}
else {
List.add(a[i]);
}
}
String ret = "";
for(int i=0; i<List.size();i++) {
ret +=List.get(i);
}
return ret;
}
public static void main(String[] args) {
System.out.print(DI("112234566778"));
}
}
s = input()
result = []
for i in range(len(s)):
if i+1 < len(s):
if int(s[i]) % 2 == 0 and int(s[i+1]) % 2 == 0:
result.append(s[i] + "*")
elif int(s[i]) % 2 != 0 and int(s[i+1]) % 2 != 0:
result.append(s[i] + "-")
else:
result.append(s[i])
print("".join(result) + s[-1])
# s = "4546793" # 454*67-9-3
# s = "477734702349" # 47-7-7-3470*2349
파이썬입니다.
def dashInsert():
# TO MAKE SURE THAT USERS INPUT ONLY NUMBERS.
nums = 'Wrong'
while not nums.isdigit():
nums = input('Please type a number: ')
# NEW EMPTY STRING TO REARRANGE WITH SYMBOLS(*, -).
output_num = ""
for i in range(len(nums)-1):
# TO KEEP COMPARING, SECOND ARGUMENTS LEAVE IN INPUT STRING.
if int(nums[i]) % 2 == 0 and int(nums[i+1]) % 2 == 0:
output_num += (nums[i] + '*')
elif int(nums[i]) % 2 == 1 and int(nums[i+1]) % 2 == 1:
output_num += (nums[i] + '-')
else:
output_num += nums[i]
# SINCE LAST ARGUMENT IS STILL IN THE STRING, ADDING IT MANUALLY.
output_num += nums[-1]
return output_num
test = dashInsert()
print(test)
def DashInsert(num):
num2 = ''
for i in range(len(num)-1):
if (int(num[i])%2 == 0) & (int(num[i+1])%2 == 0):
num2 = num2 + num[i]+ '*'
i += 1
elif (int(num[i])%2 == 1) & (int(num[i+1])%2 == 1):
num2 = num2 + num[i]+ '-'
i += 1
else:
num2 = num2 + num[i]
i += 1
return num2+num[-1]
print(DashInsert('4546793'))
def DashInsert():
num = input('input:')
# print(num[3])
# print(len(num))
num1 = []
for i in range(len(num)):
if i == 0:
num1.append(num[i])
elif i != 0:
if (int(num[i-1]) % 2 == 1) and (int(num[i]) % 2 == 1):
num1.append('-')
num1.append(num[i])
elif (int(num[i-1]) % 2 == 0) and (int(num[i]) % 2 == 0):
num1.append('*')
num1.append(num[i])
else:
num1.append(num[i])
return ''.join(num1)
print(DashInsert())
def DashInsert(str):
temp = ",".join(str).split(",")
index = 0
while index < len(str):
if int(temp[index]) % 2 == 1 and int(temp[index + 1]) % 2 == 1:
temp.insert(index+1, "-")
index += 2
elif int(temp[index]) % 2 == 0 and int(temp[index + 1]) % 2 == 0:
temp.insert(index+1, "*")
index += 2
else:
index +=1
i=0
while i<9:
print(temp[i], end='')
i += 1
DashInsert("4546793")
str1=input()
list1=[]
for i in range(len(str1)-1):
if int(str1[i])%2==0 and int(str1[i+1])%2==0:
list1.append(str1[i])
list1.append("*")
elif int(str1[i])%2!=0 and int(str1[i+1])%2!=0:
list1.append(str1[i])
list1.append("-")
else:
list1.append(str1[i])
list1.append(str1[len(str1)-1])
for i in list1:
print(i,end="")
package Lv1_2;
import java.util.ArrayList;
import java.util.Scanner;
public class DashInsert2 {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
ArrayList<String> dash = new ArrayList<String>();
// String을 갖고있는 자료타입(클래스타입)을 명시해준다.
System.out.print("정수 입력 >");
String num = sc.next();
String[] strArray = num.split("");
// split 함수로 입력한 문자열 잘라서 배열에 넣기
// 문자열을 자른 배열을 strArray로 가진 인덱스 만큼 넣고
for (int i = 0; i < strArray.length; i++ ) {
dash.add(i,strArray[i]);
// 배열리스트 Dash 인덱스에 i칸씩 집어넣는다.
}
for (int j =0; j<dash.size()-1; j++) {
// 배열리스트의 길이 만큼 반복할건데 마지막 -1인 이유는
// 그 끝 index가 바로 앞 index와 비교할 값이 존재하지 않아서 조건걸음
// 애초에 안하면 오류남
if(dash.get(j).contentEquals("-") || dash.get(j).contentEquals("*")) {
// 배열리스트의 있는 j 인덱스가 이미 "-","*" 존재하면
// continue; 무시
continue;
}
else if (Integer.parseInt(dash.get(j))%2 == 0 && Integer.parseInt(dash.get(j+1))%2 == 0) {
// 배열리스트에 있는 문자열을 정수로 변한하여 2로 나누어 계산 때릴 때
// 연속적으로 (한단계 높은 인덱스도) 짝수라면 *을 집어넣기
dash.add(j+1,"*");
} else if (Integer.parseInt(dash.get(j))%2==1 && Integer.parseInt(dash.get(j+1))%2 == 1 ) {
// 위 계산처럼 마찬가지로 홀수가 연속적 이면 "-"
dash.add(j+1, "-");
}
}
// 향상 for문으로 배열리스트 확인하기
for (String str : dash) {
System.out.print(str);
}System.out.println();
sc.close(); //스캐너 닫아버리기
}
}
strnum = input("숫자로 된 문자열 입력 받기:")
result = []
result.append(strnum[0])
for i in range(len(strnum)-1):
if int(strnum[i]) % 2 == 0 and int(strnum[i+1]) % 2 == 0:
word = '*' + strnum[i+1]
result.append(word)
elif int(strnum[i]) % 2 == 1 and int(strnum[i+1]) % 2 == 1:
word = '-' + strnum[i+1]
result.append(word)
else:
result.append(strnum[i+1])
print(''.join(result))
dash=input("write numbers :")
new=[]
new.append(dash[0])
for i in range(0,len(dash)-1,1):
if int(dash[i])%2==0 and int(dash[i+1])%2==0:
new.append("*")
elif int(dash[i])%2==1 and int(dash[i+1])%2==1:
new.append("-")
new.append(dash[i+1])
print("".join(new))
def DashInsert(text):
result = list(text)
length = len(text)
for i,j in zip(range(length-1),range(1,length)):
if (int(result[i])+int(result[j]))%2==0:
if int(result[i])%2==0:
result[i]=result[i]+'*'
else :
result[i]=result[i]+'-'
return ''.join(result)
a = input("숫자를 입력하세요:")
def temp(a):
list = [a[0]]
for i in range(1, len(a)):
if ((int(a[i]) + int(a[i-1])) % 2 == 0) and ((int(a[i]) * int(a[i-1])) % 2 == 0):
list.append('*')
list.append(a[i])
elif ((int(a[i]) + int(a[i-1])) % 2 == 0) and ((int(a[i]) * int(a[i-1])) % 2 != 0):
list.append('-')
list.append(a[i])
elif ((int(a[i]) + int(a[i-1])) % 2 != 0):
list.append(a[i])
result = ''
for j in range(0, len(list)):
result = result + list[j]
return result
temp(a)
def DashInsert(n):
n = str(n)
output= list(n[:2])
for i in range(2, len(n)):
if int(n[i-1]) % 2 != int(n[i]) % 2 :
output.append(n[i])
elif int(n[i-1]) % 2 == 0 and int(n[i]) % 2 == 0:
output.append(f'*{n[i]}')
else:
output.append(f'-{n[i]}')
return output
for x in DashInsert(4546793):
print(x, end="")
def main():
N = list(str(4546793)) #list(input('Number : ')) # N is string
i = 1
while i < len(N):
if int(N[i])*int(N[i-1])%2 != 0:
N.insert(i,'-')
i += 1
elif int(N[i])%2 == 0 and int(N[i-1])%2 == 0:
N.insert(i,'*')
i += 1
i += 1
return N
if __name__ == '__main__':
N = main()
num = "4446773"
list = []
for i in range(len(num) - 1):
list.append(num[i])
if int(num[i]) % 2 == 0 and int(num[i+1]) % 2 == 0:
list.append('*')
if int(num[i]) % 2 == 1 and int(num[i+1]) % 2 == 1:
list.append('-')
list.append(num[-1])
print("".join(list))
N = input("정수를 입력하세요")
n = list(str(N))
for i in range(len(N)-1):
if int(n[i]) % 2 == 0 and int(n[i+1]) % 2 == 0:
n[i] = n[i] + "*"
elif int(n[i]) % 2 == 1 and int(n[i+1]) % 2 == 1:
n[i] = n[i] + "-"
print("".join(n))
이거 하나 짜는데 30분이나 걸리네요 ...
munja=input('입력')
def DashInsert(e):
result=''
for i in range(len(e)):
result=result+e[i]
if e[i] == e[-1] :
break
if int(e[i]) %2 == 0 and int(e[i+1]) % 2 == 0 :
result=result+'*'
if int(e[i]) %2 == 1 and int(e[i+1]) % 2 == 1 :
result=result+'-'
return result
print(DashInsert(munja))
num = input('숫자: ')
result = ''
for i in range(len(num)):
result += num[i]
if i == len(num)-1:
break
if int(num[i])%2== 0 and int(num[i+1])%2== 0:
result += '*'
elif int(num[i])%2 != 0 and int(num[i+1])%2 != 0:
result += '-'
print(result)
Python입니다.
>>> def dash_insert(s):
... result = ''
... for i in range(len(s)):
... result += s[i]
... if i != 0 and i < len(s) - 1:
... if int(s[i]) % 2 == 0 and int(s[i + 1]) % 2 == 0:
... result += '*'
... elif int(s[i]) % 2 == 1 and int(s[i + 1]) % 2 == 1:
... result += '-'
... return result
...
>>> dash_insert('4546793')
'454*67-9-3'
a=input("숫자를 입력해주세요")
new_string = '{}'.format(a[0])
for i in range(1,len(a)):
if int(a[i])%2 == 0:
if int(a[i-1])%2 == 0:
new_string=new_string+'*'+a[i]
else :
new_string=new_string+a[i]
else:
if int(a[i-1])%2 == 0:
new_string=new_string+a[i]
else:
new_string=new_string+'-'+a[i]
print(new_string)
def dash_insert():
num = input("숫자열 입력 : ")
new_list = []
for i in range(0, len(num) - 1):
if int(num[i]) % 2 == 0 and int(num[i + 1]) % 2 == 0:
new_list.append(num[i] + "*")
elif int(num[i]) % 2 != 0 and int(num[i + 1]) % 2 != 0:
new_list.append(num[i] + "-")
else:
new_list.append(num[i])
new_list.append(num[len(num) - 1])
result = "".join(new_list)
return result
#codingdojing_dashinsert
firstStr = input('enter the number: ') #4546793
finalStr = ''
for i in range(len(firstStr)-1):
finalStr += firstStr[i]
is_even = int(firstStr[i])%2 == 0
is_even2 = int(firstStr[i+1])%2 == 0
if is_even & is_even2:
finalStr += '*'
elif (not is_even) & (not is_even2):
finalStr += '-'
finalStr += firstStr[-1]
print(finalStr)
파이썬으로 작성했습니다.
import re
def is_even(n):
if int(n) % 2 == 0:
return 0
else:
return 1
def DashInsert(numbers):
result = []
last_one = is_even(numbers[0])
current_one = 0 # 현재 짝수이면 0, 홀수이면 1
result.append(numbers[0])
for i in range(1, len(numbers)):
current_one = is_even(numbers[i])
if current_one == last_one:
if current_one:
result.append('-')
else:
result.append('*')
result.append(numbers[i])
last_one = current_one
return print(''.join(result))
n = '123123'
numbers = input('숫자로만 구성된 문자열을 입력 : ')
while len(re.sub('[0-9]*', '', numbers)) > 0:
print('숫자만 입력하라고!!')
numbers = input('숫자로만 구성된 문자열을 입력 : ')
DashInsert(numbers)
def DashInsert(str_a):
# str_a에 있는 문자 하나에 대해서
prev = []
answer = ''
# 각각의 숫자에 대해서
for s in str_a:
if len(prev) == 0: # 첫번째 숫자라면
prev.append(int(s))
answer+=s
continue
else: #두번째 숫자부터는
#이전 숫자와 현재 숫자가 둘 다 홀수 라면
if (prev[0]%2==1) and (int(s)%2==1):
answer+='-'
#이전 숫자와 현재 숫자가 둘 다 짝수 라면
elif (prev[0]%2==0) and (int(s)%2==0):
answer+='*'
#그 이외의 경우라면
answer+=s
#현재 숫자를 prev에 저장
prev[0] = int(s)
return answer
if __name__ == '__main__':
a = input('숫자: ')
str_a = str(a)
print(DashInsert(str_a))
def DashInsert(n):
result=''
for i in range(len(n)-1):
result+=n[i]
if int(n[i])%2==0 and int(n[i+1])%2==0:
result+='*'
if int(n[i])%2==1 and int(n[i+1])%2==1:
result+='-'
result+=n[-1]
return result
user_input=input('숫자를 입력하세요 : ')
print(DashInsert(user_input))
def DashInsert():
num = list(input('숫자를 입력하세요: '))
indexlist = []
for elnum in num:
if int(elnum)%2 == 0:
indexlist += [0]
else:
indexlist += [1]
for i in range(len(num)-1):
print(num[i], end='')
if indexlist[i] == indexlist[i+1] and indexlist[i] == 0:
print('*', end='')
elif indexlist[i] == indexlist[i+1] and indexlist[i] == 1:
print('-', end='')
print(num[-1])
DashInsert()
s=input("숫자를 입력하세요: ")
for i in range(1,len(s)):
print(f'{s[i-1]}',end='')
if int(s[i-1])%2==0 and int(s[i])%2==0: print('*',end='')
elif int(s[i-1])%2==1 and int(s[i])%2==1: print('-', end='')
print(s[-1])
static void DashInsert(String x) {
for(int i = 0; i< x.length(); i++) {
System.out.print(x.charAt(i)-48);
if (i< x.length()-1) {
if((x.charAt(i)-48)%2 ==(x.charAt(i+1)-48)%2) {
if((x.charAt(i)-48)%2 == 0)
System.out.print("*");
else
System.out.print("-");
}
}
}
}
public static void main(String[] args) {
DashInsert("4546793");
}
d = list(map(int,' '.join(input()).split()))
answer = [str(d[0])]
for k in range(len(d)-1) :
if d[k] %2 ==0 and d[k+1] %2 ==0 :
answer.append("*")
elif d[k] %2 ==1 and d[k+1] %2 ==1 :
answer.append("-")
answer.append(str(d[k+1]))
print(answer)
정규식은 잘 몰라서 if문으로 구현했습니다.
input_data = input()
result = input_data[0]
for digit in input_data[1:]:
if int(result[-1])%2 == int(digit)%2 == 1:
result = result + '-' + digit
elif int(result[-1])%2 == int(digit)%2 == 0:
result = result + '*' + digit
else: result += digit
print(result)
실행 결과입니다.
454
454
4546793
454*67-9-3
def Dash(n):
result = []
for i in range(len(n)-1):
result.append(n[i])
if(int(n[i])%2 == 0 and int(n[i+1])%2 == 0):
result.append('*')
elif( int(n[i])%2 == 1 and int(n[i+1])%2 == 1 ):
result.append('-')
if( i == len(n)-2):
result.append(n[len(n)-1])
return result
print(''.join(Dash(list(input("입력 :")))))
a = input('type the number')
b = []
for i in range(len(a)-1):
b.append(a[i])
if i >0:
if int(a[i])%2 ==1 and int(a[i+1])%2 == 1:
b.append('-')
if int(a[i])%2 ==0 and int(a[i+1])%2 == 0:
b.append('*')
b.append(a[-1])
print(''.join(b))
// Rust
fn main() {
let text = "4546793";
let mut iter = text.chars();
// 첫 번째 숫자를 결과에 저장
let mut result = vec![iter.next().unwrap()];
// 두 번째 숫자부터 바로 앞 숫자와의 관계를 검사해서 결과를 만들어감
for c in iter {
let current = c.to_digit(10).unwrap();
let prev = result[result.len()-1].to_digit(10).unwrap();
if prev % 2 == 0 {
if current % 2 == 0 {
result.push('*');
}
} else if current % 2 != 0 {
result.push('-');
}
result.push(c);
}
let result = result.iter().collect::<String>();
println!("{}", result);
}
user_input = input('숫자열을 입력: ')
result = ""
for i, num in enumerate(user_input):
result += num
if i < len(user_input) - 1:
now = int(num) % 2 == 1
next = int(user_input[i+1]) % 2 == 1
if now and next:
result += '-'
if not now and not next:
result += '*'
print(result)
def Dash(n):
result = []
for i in range(len(n)-1):
result.append(n[i])
if(int(n[i])%2 == 0 and int(n[i+1])%2 == 0):
result.append('*')
elif( int(n[i])%2 == 1 and int(n[i+1])%2 == 1 ):
result.append('-')
if( i == len(n)-2):
result.append(n[len(n)-1])
return result
print(''.join(Dash(list(input("입력 :")))))
l=list(map(int,' '.join(input()).split()))
l2=[str(l[0])]
for n in range(len(l)-1):
if l[n]%2==0 and l[n+1]%2==0:
l2.append("*")
elif l[n]%2==1 and l[n+1]%2==1:
l2.append("-")
else: l2.append(str(l[n+1]))
print(''.join(l2))
num = input("숫자입력: ")
numList = []
for i in range(len(num)):
numList.append(num[i])
try:
if int(num[i]) % 2 == 0 and int(num[i+1]) % 2 == 0:
numList.append('*')
elif int(num[i]) % 2 == 1 and int(num[i+1]) % 2 == 1:
numList.append('-')
except: pass
print(''.join(numList))
package com.algorithm.algorithmpractice.dojang;
import java.util.ArrayList;
public class DashInsert {
public static void main(String[] args) {
char prev;
String input = "4546793";
ArrayList<Character> newChar = new ArrayList<>();
prev = input.charAt(0);
newChar.add(prev);
for(int i = 1; i < input.length(); i++){
if(Integer.valueOf(prev)%2 == 1 && Integer.valueOf(input.charAt(i))%2 == 1){
newChar.add('-');
newChar.add(input.charAt(i));
prev = input.charAt(i);
continue;
}
if(Integer.valueOf(prev)%2 == 0 && Integer.valueOf(input.charAt(i))%2 == 0){
newChar.add('*');
newChar.add(input.charAt(i));
prev = input.charAt(i);
continue;
}
newChar.add(input.charAt(i));
prev = input.charAt(i);
}
StringBuffer sb = new StringBuffer();
newChar.forEach(elem -> {
sb.append(elem);
});
String result = sb.toString();
System.out.println(result);
}
}
반복문에서 중복 제거 하기.
def Dashinsert(a):
b = a[0]
for i in range(len(a)-1) :
if (int(a[i]%2)== 0 )& (int(a[i+1]) == 0 ):
b+="*"
elif (int(a[i]%2)== 1) & (int(a[i+1]) == 1) :
b+="-"
b+=a[i+1]
return b
python
#Dash Insert
sample = input()
#sample = '4546793'
result = sample[0]
for i in range(len(sample)-1):
if int(sample[i]) % 2 == 1 and int(sample[i+1]) % 2 == 1:
result += '-' + sample[i+1]
elif int(sample[i]) % 2 == 0 and int(sample[i+1]) % 2 == 0:
result += '*' + sample[i+1]
else:
result += sample[i+1]
print(result)
string을 사용하면 concat이나 삽입할때, 속도 우려가 있어서 stringbuilder를 활용해봤습니다. 1. 해당숫자와 다음숫자 홀짝판별 메소드 사용 2. 연속되는 홀,짝인 경우에만 특수문자 삽입
//홀수사이에는- 짝수사이에는*
private static StringBuilder DashInsert(String num) {
StringBuilder sbNum = new StringBuilder();
for(int i=0; i<num.length(); i++) {
if(i == num.length()-1) {
sbNum.append(num.charAt(i));
}else if(oddNumber(Integer.parseInt(String.valueOf(num.charAt(i)))) && oddNumber(Integer.parseInt(String.valueOf(num.charAt(i+1)))) ) {
sbNum.append(num.charAt(i));
sbNum.append("*");
}else if(!oddNumber(Integer.parseInt(String.valueOf(num.charAt(i)))) && !oddNumber(Integer.parseInt(String.valueOf(num.charAt(i+1))))) {
sbNum.append(num.charAt(i));
sbNum.append("-");
}else {
sbNum.append(num.charAt(i));
}
}
return sbNum;
}
//홀짝판별메소드
private static boolean oddNumber(int n) {
boolean number = (n%2) == 0 ? true : false; //짝수:true
return number;
}
def dash_insert(x) :
a=str(x)
b=len(a)
List_s=[]
List_n=[]
d=0
for c in range(b-1):
if ((int(a[c]))%2==0) and ((int(a[c+1]))%2 == 0):
List_s.append('*')
List_n.append(c)
elif ((int(a[c]))%2==1) and ((int(a[c+1]))%2 == 1):
List_s.append('-')
List_n.append(c)
else :
pass
for n in List_n:
a=a[:n+d+1]+List_s[d]+a[n+d+1:]
d+=1
return a
print(dash_insert(4546793))
def DashInsert(str):
newStr = ''
for i in range(len(str) - 1):
if (int(str[i]) % 2 == 0 and int(str[i+1]) % 2 == 0):
newStr += (str[i] + '*')
elif (int(str[i]) % 2 == 1 and int(str[i+1]) % 2 == 1):
newStr += (str[i] + '-')
else :
newStr += str[i]
newStr += str[len(str) - 1]
print(newStr)
DashInsert('4546793')
Python
strInput=input()
def DashInsert(str1):
list1=list(str1)
for i in range(len(list1)-1,0,-1):
if int(list1[i])%2==0 and int(list1[i-1])%2==0:
str1=str1[:i]+"*"+str1[i:]
elif int(list1[i])%2==1 and int(list1[i-1])%2==1:
str1=str1[:i]+"-"+str1[i:]
return str1
print(DashInsert(strInput))
def DashInsert(num):
dash_num = ''
dash_chk = ''
for i in num:
ix = int(i)
if ix % 2 == 0: #짝수
if dash_chk == 'E':
dash_num = dash_num + '*'
dash_chk = 'E'
else:
if dash_chk == 'O':
dash_num = dash_num + '-'
dash_chk = 'O'
dash_num = dash_num + i
return dash_num
#main_
input_num = input("정수문자열 입력 : ")
print(DashInsert(input_num))
data = list(map(str,input("Enter:")))
result = []
for i in range(len(data)):
result.append(data[i])
if i < len(data)-1:
a = int(data[i]) % 2 ; b = int(data[i+1]) % 2
if a > 0 and b > 0 :
result.append('-')
elif a == 0 and b == 0:
result.append('*')
else:continue
else:break
print(''.join(result))
a=(input("원하는 숫자들을 입력하세요")) def DashInsert(x): b='' for i in range(0,len(x)-1): if int(x[i])%2 == 0 and int(x[i+1])%2 ==0: b += x[i]+'*' elif int(a[i])%2 != 0 and int(x[i+1])%2 !=0: b += x[i]+'-' else: b += x[i] return b
b = DashInsert(a) print(b)
input_ = input('숫자로 된 문자열을 입력: ')
answer = input_[0]
for i in range(1, len(input_)):
if int(input_[i-1]) % 2 == 0 and int(input_[i]) % 2 == 0:
answer += '*'
elif int(input_[i-1]) % 2 == 1 and int(input_[i]) % 2 == 1:
answer += '-'
answer += input_[i]
print(answer)
방법1.
from functools import reduce
check = lambda x,y: (x%2 and y%2) and '-' or not(x%2 or y%2) and '*' or ''
DashInsert = lambda numStr: reduce(lambda x,y: x + check(int(x[-1]), int(y)) + y, numStr)
print('결과:', DashInsert(input('숫자 입력:')))
> 숫자 입력: 4546793
> 결과: 454*67-9-3
방법2.
check = lambda x,y: ['*','','-'][int(x)%2+int(y)%2]
DashInsert = lambda d: d[0] + ''.join([check(d[i-1], d[i]) + d[i] for i in range(1, len(d))])
print('결과:', DashInsert(input('숫자 입력:')))
> 숫자 입력: 4546793
> 결과: 454*67-9-3
def DashInsert():
m = input("Enter the number : ")
even = ['2','4','6','8','0']
odd = ['1','3','5','7','9']
results = ""
for i in range(len(m)-1):
results += m[i]
if (m[i] in even) and (m[i+1] in even) :
results += "*"
if (m[i] in odd) and (m[i+1] in odd) :
results += "-"
results += m[-1]
return results