시저 암호는, 고대 로마의 황제 줄리어스 시저가 만들어 낸 암호인데, 예를 들어 알파벳 A를 입력했을 때, 그 알파벳의 n개 뒤에 오는(여기서는 예를 들 때 3으로 지정하였다)알파벳이 출력되는 것이다. 예를 들어 바꾸려는 단어가 'CAT"고, n을 5로 지정하였을 때 "HFY"가 되는 것이다.
어떠한 암호를 만들 문장과 n을 입력했을 때 암호를 만들어 출력하는 프로그램을 작성해라.
192개의 풀이가 있습니다.
def enig(inp, n) :
s, res = 'aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ', ''
for M in inp :
if M in s : res += s[(s.index(M)+2*n)%52]
else : res += M
return res
INP = str(input("INPUT : "))
N = int(input("N : "))
print(enig(INP, N))
다른분들의 풀이와 거의 비슷하지만, 대문자와 소문자의 처리를 좀더 간편하게 할 수 있는 방법을 생각해보았습니다.
결과
INPUT : CAT, dog
N : 5
HFY, itl
text, k = input(), int(input())
caesar = lambda x: chr(ord(x)+ k % 26) if x.isalpha() else x
print(''.join(caesar(ch) for ch in text))
def caesar(P, n=3):
C = []
for char in P:
if char.isalpha():
if char.isupper():
C.append( chr((ord(char)-ord('A') + n) % 26 + ord('A')) )
else:
C.append( chr((ord(char)-ord('a') + n) % 26 + ord('a')) )
else:
C.append(char)
return ''.join(C)
파이썬3로 무식하게 풀어보았습니다...
Python 3으로 풀었습니다.
def caesar(s, n):
pre_defined = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
n = n % len(pre_defined)
transform = pre_defined[n:] + pre_defined[:n]
return ''.join([transform[pre_defined.find(_)] for _ in s])
파이썬
key_input = input("암호 키를 입력하시오")
str_input = input("암호화할 문자를 입력하시오")
result = ""
for n in str_input :
temp = ord(n) + (int)(key_input)
result = result + chr(temp)
print(result)
# 한글 처리 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')
# 시저 암호는, 고대 로마의 황제 줄리어스 시저가 만들어 낸 암호인데, 예를 들어 알파벳 A를 입력했을 때,
# 그 알파벳의 n개 뒤에 오는(여기서는 예를 들 때 3으로 지정하였다)알파벳이 출력되는 것이다.
# 예를 들어 바꾸려는 단어가 'CAT"고, n을 5로 지정하였을 때 "HFY"가 되는 것이다.
# 어떠한 암호를 만들 문장과 n을 입력했을 때 암호를 만들어 출력하는 프로그램을 작성해라.
sentence = input("문장을 입력하세요 : ")
n = int(input("n : "))
caesar = ""
for i in range(len(sentence)):
char = sentence[i]
char_number = ord(char)
# 소문자 변환
if char.islower():
char_number = (char_number + n - ord('a')) % 26 + ord('a')
# 대문자 변환
elif char.isupper():
char_number = (char_number + n - ord('A')) % 26 + ord('A')
caesar += chr(char_number)
print(sentence, "===>", caesar)
# print(ord('a'), ord('z'), ord('A'), ord('Z'), chr(65))
def solution(s, n):
alpha = "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ"
output = ""
for i in s:
if i in alpha:
output = output + alpha[(alpha.index(i) + 2*n) % 52]
else:
output = output + i
return output
word = input("Enter words: ")
num = int(input("Decide number: "))
print(solution(word, num))
Ruby
ch = ->n,a=[*'A'..'Z'] { a.zip(a.rotate n).to_h }
tr = ->str,n { puts str.gsub(/./, ch[n]) }
Test
expect { tr["A", -1] }.to output("Z\n").to_stdout
expect { tr["ZZ", 5] }.to output("EE\n").to_stdout
expect { tr["CAT", 5] }.to output("HFY\n").to_stdout
import java.util.Scanner;
public class Caesar {
public static void main(String[] args) {
String A="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String ans="";
int adress;
Scanner s= new Scanner(System.in);
System.out.println("문자열 입력 : ");
String word=s.nextLine();
System.out.println("n을 입력 :");
int n=s.nextInt();
n=n%26; // 한바퀴 돌 경우 대비
for(int i=0;i<word.length();i++) {
String cnt=word.substring(i,i+1);
if(cnt.equals(" ")) {
ans=ans+" ";
continue;
}
adress=A.indexOf(cnt);
ans=ans+A.substring(adress+n,adress+(n+1));
}
System.out.println(ans);
}
}
R로 작성하였습니다.
trans <- function(x,n) {
a <- 1:length(LETTERS)
names(a) <- LETTERS
b <- LETTERS
names(b) <- 1:length(LETTERS)
result <- NULL
char <- unlist(strsplit(x, ""))
for(i in 1:length(char)){
result[i] <- b[a[char[i]]+n]
}
return(result)
}
user_input=raw_input('Input: ')
secret_code=raw_input('Input secret_code: ')
secret_code=int(secret_code)
ceaser_code=[]
for i in range(len(user_input)):
ceaser_code.append(chr(ord(user_input[i])+secret_code))
ceaser_code=''.join(ceaser_code)
print('Ceaser code: %s'%ceaser_code)
C
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc,char* argv[])
{
if(argc != 3)
{
printf("no argc 3 !!!\n");
}
char* str = (char*)malloc(sizeof(char)*64);
str = argv[1];
for(int i=0;i<strlen(str);i++)
{
int tmp = (int)str[i] + atoi(argv[2]);
if((int)str[i]<90 && tmp>90)
tmp = tmp - 90 + 64;
else if((int)str[i]>97 && tmp>122)
tmp = tmp - 122 + 96;
str[i] = (char)tmp;
}
printf("%s",str);
return 0;
}
#시저 암호풀기
dic = 'abcdefghijklmnopqrstuvwxyz'
a= []
#word는 입력받는 단어
#num은 코드
#위치를 받을 변수 p
def decode(word, num):
for i in range(0, len(word)):
p = dic.find(word[i])
a.append(dic[p + num])
return a
word = input("영어단어를 입력해주세요")
print(decode(word , 5))
x = [ord(i) for i in input('입력')]
num = int(input('변환숫자'))
a = map(lambda k : k+num, x)
print([chr(y) for y in a])
def f(str1, n):
s1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
str1 = list(str1)
for idx1, chr1 in enumerate(str1):
a = s1.index(chr1) + n
str1[idx1] = s1[a%len(s1)]
print(''.join(str1))
f('CAT',5)
a=input("바꾸려는 문장 :")
n=int(input("변경코드: "))
result=""
for i in range(len(a)):
result=result+chr(ord(a[i])+n)
print(result)
import java.util.Scanner;
public class Example138 {
public static void main(String[] args) {
Example138 ex = new Example138();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String s = "zZZ";
System.out.println(ex.getEncryption(s, n));
}
private String getEncryption(String s, int n) {
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
if (Character.isAlphabetic((char) (c + n))) {
c = (char) (c + n);
} else {
if (Character.isLowerCase(c)) {
c = (char) (96 + (c + n) - 'z');
} else {
c = (char) (64 + (c + n) - 'Z');
}
}
sb.append((char) (c));
}
return sb.toString();
}
}
일단 char + n 형태로 구했는데.. z나 Z가 넘어가면 다시 a or A 부터 시작하겠습니다. Character.isAlphabetic로 범위 넘어갔나 체크했습니다.
// golang 1.9
package main
import "fmt"
func main() {
inpStr := "CATABCDEFGHIJKLMNOPQRSTUVWXYZ" // input string
nMove := 5 // 알파벳 이동량
outStr := ""
for _, v := range inpStr { // 문자열에 대해
mvAmnt := int(v) + nMove // 아스키 값을 증가 이동
if mvAmnt > 90 {
mvAmnt = mvAmnt - 90 + 64 // Z를 넘어갈 경우 A로 순환
}
outStr += string(mvAmnt)
}
fmt.Println("String input : ", inpStr)
fmt.Println("String output: ", outStr)
}
/* ans:
String input : CATABCDEFGHIJKLMNOPQRSTUVWXYZ
String output: HFYFGHIJKLMNOPQRSTUVWXYZABCDE
*/
#include <iostream>
using namespace std;
int main() {
char msg[1000];
int key;
cin >> msg;
cin >> key;
cout << msg << " >> ";
for (int i = 0; i < strlen(msg); i++)
msg[i] += key;
cout << msg << endl;
return 0;
}
python 2.7
def fp(key, n):
alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
pw = str()
for i in key:
pw += (alpha[alpha.index(i) + n % 26])
return pw
# python 3.6
# ord("A")= 65, ord("Z") = 90
n = int(input("n: "))
inp = input("string: ").upper()
if inp.isalpha(): # 대문자가 입력된 경우에 한하여 수행
# "Z"를 넘어갈 경우 "A" 부터 순환
cnv = "".join([chr(ord(c) + n) if ord(c) + n <=
90 else chr(ord(c) - 90 + 64 + n) for c in inp])
print("converted: ", cnv)
package org.Solve_5;
import java.util.Scanner; import java.util.ArrayList;
public class Solve_5 { public static void main(String[] agrs){ System.out.println("hello");
InputData a1 = new InputData();
a1.InputData();
for (int a=0; a<a1.result.size(); a++){
System.out.println(a1.result.get(a));
}
}
}
class InputData{ String inputdata; int n; ArrayList alphabat = new ArrayList(); ArrayList inputdata_list = new ArrayList(); ArrayList inputdata_number = new ArrayList();
ArrayList inputdata_new_number = new ArrayList();
ArrayList result = new ArrayList();
public void InputData(){
alphabat.add("a");
alphabat.add("b");
alphabat.add("c");
alphabat.add("d");
alphabat.add("e");
alphabat.add("f");
alphabat.add("g");
alphabat.add("h");
alphabat.add("i");
alphabat.add("j");
alphabat.add("k");
alphabat.add("l");
alphabat.add("m");
alphabat.add("n");
alphabat.add("o");
alphabat.add("p");
alphabat.add("q");
alphabat.add("r");
alphabat.add("s");
alphabat.add("t");
alphabat.add("u");
alphabat.add("v");
alphabat.add("w");
alphabat.add("x");
alphabat.add("y");
alphabat.add("z");
System.out.println("암호화 할 문장을 입력해주세요 : ");
Scanner sc2 = new Scanner(System.in);
inputdata = sc2.nextLine();
System.out.println("암호화 할 횟수를 입력해주세요 : ");
Scanner sc1 = new Scanner(System.in);
n = sc1.nextInt();
int data_length = inputdata.length();
for (int a =0; a<data_length; a++){
String test1 = inputdata.substring(a,a+1);
inputdata_list.add(test1);
}
for (int t =0; t < inputdata_list.size(); t ++){
inputdata_number.add(alphabat.indexOf(inputdata_list.get(t)));
}
for (int h =0; h < inputdata_number.size(); h ++){
inputdata_new_number.add((int)inputdata_number.get(h) + n);
}
for (int z =0; z<inputdata_new_number.size();z++){
result.add(alphabat.get((int)inputdata_new_number.get(z)));
}
}
}
#include <stdio.h>
#include <string.h>
int main(void) {
char s[100], a[100];
int e_num;
// 암호화할 문자열(공백포함)을 입력받아 배열에 담고, n값을 입력 받는다.
printf("Input a sentence for encoding. : ");
scanf("%[^\n]s",s);
printf("Enter encoding number. : ");
scanf("%d", &e_num);
// 입력받은 문장의 길이를 구한다.
int len =strlen(s);
// 배열내 문자의 ASCII값에 n값을 더하여, 암호화된 문장으로 바꾼다.
for (int i=0; i<len ;i++) {
// 단, 'Z'를 넘어갈 경우는 'A'부터 다시 계산되게 한다.
if (s[i]>='A' && s[i]<= 'Z') {
if (s[i]+e_num > 'Z') a[i] = (s[i]+e_num-('Z'-'A'+1));
else a[i] = s[i]+e_num;
}
// 마찬가지로, 'z'를 넘어갈 경우도 'a'부터 다시 계산되게 한다.
else if (s[i]>='a' && s[i]<= 'z') {
if (s[i]+e_num > 'z') a[i] = (s[i]+e_num-('z'-'a'+1));
else a[i] = s[i]+e_num;
}
// 그 외, 알파벳을 제외한 모든 문자는 그대로 출력되게 한다.
else a[i] = s[i];
}
// 암호화된 문장을 출력한다.
printf("%s\n",a);
return 0;
}
def cesar(n, string):
small = 'abcdefghijklmnopqrstuvwxyz'
capital = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
res = ''
for c in string:
if c in small:
res += small[(small.index(c) + n) % 26]
elif c in capital:
res += capital[(capital.index(c) + n) % 26]
else:
res += c
return res
print(cesar(5, 'Hello World!'))
python 2.7
def ceasar(str, n):
alphabet_lst = [x for x in "abcdefghijklmnopqrstuvwxyz"]
str_lst = [x for x in str]
for i in range(len(str_lst)):
str_lst[i] = alphabet_lst[(alphabet_lst.index(str_lst[i]) + n) % 26]
ceasar = "".join(str_lst)
return ceasar
print (ceasar("cat", 5))
python
STR = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
print((lambda alphabet, n : ("".join([(STR[STR.find(i) + n]) if STR.find(i) + n <= 52 else (STR[STR.find(i) + n - 52]) for i in alphabet])))(alphabet = input('alphabet : '), n = int(input('n : '))))
이건 아닌 듯 해서
low = 'abcdefghijklmnopqrstuvwxyz'
up = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def signal(string, n, code = ''):
for i in string:
if i.islower():
if low.find(i) + n > 25: i = low[low.find(i) + n - 26]
else: i = low[low.find(i) + n]
else:
if up.find(i) + n > 25: i = up[up.find(i) + n - 26]
else: i = up[up.find(i) + n]
code += i
return code
print(signal('abcxXyYzZ', 3))
a=['A','B','C','D','E','F','G','H','I','J','K','L','M',
'N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
def code(n,d):
sol=[]
for x in n.upper():
if x==' ':sol.append(' ')
else:
f=a.index(x)
if f+d>25:sol.append(a[(f+d)-26])
else:
sol.append(a[f+d])
for i in sol:
print(i,end='')
A='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
n=int(input('n: '))%len(A)
string=list(str(input(('sentence: '))).upper())
B=A[n:]+A[:n]
for i in range(len(string)):
if string[i] in A:
string[i]=B[A.find(string[i])]
print(''.join(string))
#!/usr/bin/env python
input_alp=raw_input('enter your alpha >>> ')
input_key=input('enter you key >>> ')
def make_passwd(char, key):
raw_alpha = 'abcdefghigklmnopqrstuvwxyz'
pass_index=(raw_alpha.index(char) + input_key)
return(raw_alpha[pass_index])
def main():
passwd=[]
for i in input_alp:
passwd += make_passwd(i, input_key)
print(passwd)
if __name__ == '__main__':
main()
A = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; Alp = [] for i in range(len(A)): Alp.append(A[i])
Sec = {} Sec2 = {} Pass = []
for i in range(len(A)): Sec[A[i]] = i+1 Sec2[i+1] = A[i]
B = input("알파벳을 입력하시오. : ") N = input("시저숫자를 입력하시오. : ") C = [] for j in range(len(B)): C.append(B[j])
for i in range(len(C)): Pass.append(Sec[C[i]]) if Pass[i]+int(N) <= 26: print(Sec2[Pass[i]+int(N)]) else: print(Sec2[Pass[i]+int(N)-26])
# 파이썬 초보입니다
sentence = input("문장을 입력하시오: ")
n = int(input("숫자를 입력하시오: "))
total = ""
for i in range(len(sentence)):
script = sentence[i]
script_return = ord(script) + n
total += chr(script_return)
print(total)
파이썬 3.6
string = input(" ▶ 문장을 입력하세요 : ")
n = int(input(" ▶ n 값을 입력하세요 : "))
print("\n",">>> password : ",''.join([chr(ord(i)+n) for i in string]))
*결과값
▶ 문장을 입력하세요 : CAT
▶ n 값을 입력하세요 : 5
>>> password : HFY
파이썬 입니다.
abc=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
def dcy(s,a):
result=[]
n=len(s)
for x in s:
if (abc.index(x)+a)>=len(abc):
print('%s'%abc[((abc.index(x)+a)-len(abc))-1],end="")
else:
print('%s'%abc[abc.index(x)+a],end="" )
dcy('bzzy',4)
#include <stdio.h>
#include <string.h>
int main(void) {
char str[200];
int n;
printf("Input str: ");
scanf("%s", str);
printf("Input N: ");
scanf("%d", &n);
int i;
for (i = 0; i < strlen(str); i++)
str[i] = str[i] + n;
printf("Password is: %s\n\n", str);
return 0;
}
apv = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R","S", "T", "U", "V", "W", "X", "Y", "Z"]
s = int(input("숫자를 입력하세요"))
w = str(input("단어를 입력해주세요"))
w = list(w)
for q in range(0, len(w)):
for e in range(0, len(apv)):
if w[q] == apv[e]:
d = e+s
if 25 < d:
d = e+s-25
w[q] = apv[d]
break
print(w)
n = int(input("n:"))
sentence1 = input("문장:")
alph = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
s = list(map(str,' '.join(sentence1).split()))
sentence2 = []
for i in s:
i = alph[alph.index(i)+n]
sentence2.append(i)
print(''.join(sentence2))
s = input("문장을 입력하시오 : ")
n = int(input("수를 입력하시오(0~25) : "))
def caserpassword(str, number):
c = ''
for i in range(len(str)):
if ord(str[i])+number <= 90:
c += chr(ord(str[i])+number)
else:
c += chr(ord(str[i]+number-26))
return c
print(caserpassword(s,n))
a-zA-Z 에서 Z다음은 다시 소문자로 돌아오게 했습니다
for_password_str=input("암호로 바꾸려는 문자열을 입력하세요\n")
key=int(input("N을 입력하세요\n"))
password_str=''
for k in for_password_str:
temp_num=ord(k)+key
if k.isupper()==True:
if temp_num>90:
password_str+=chr((temp_num%90)+96)
else:
password_str+=chr(temp_num)
else:
if temp_num>122:
password_str+=chr((temp_num%122)+64)
else:
password_str+=chr(temp_num)
print(password_str)
public class passwordTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("문장을 이력하세요 :");
String str = scanner.nextLine();
StringBuffer sb = new StringBuffer();
for(int i = 0; i < str.length(); i++) {
if((str.charAt(i) + "").matches("[a-zA-Z]")) {
sb.append((char)(str.charAt(i) + 5));
} else {
sb.append(str.charAt(i));
}
}
System.out.println("입력한 문장 :" + str);
System.out.println("시저 암호 문장 :" + sb);
scanner.close();
}
}
def ceasar(sen, n):
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
result = ''
for char in sen:
count = 0
while char != alphabet[count]:
count = count + 1
if count > len(alphabet) - n: result = result + alphabet[count + n - 26]
else: result = result + alphabet[count + n]
return result
Python 3
a = input("Enter: ")
b = int(input("Enter: "))
result = ""
a = upper()
for x in a:
if x.isalpha():
num = ord(x)+b
if num > ord('Z'):
num = num-ord('Z') + ord('A') -1
result += chr(num)
else:
result += x
print(result)
def ceaser(string,num) :
eng = 'abcdefghijklmnopqrstuvwxyz'
new = ""
for i in string :
if i.isalpha() == False : new += i
for j in range(26) :
if i.lower() == eng[j] :
if i.isupper() == True :
new += eng[(j + num) % 26].upper()
else :
new += eng[(j + num) % 26]
return new
Swift입니다.
import Foundation
var moveCount = 5
var alphabet = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
var message = Array(readLine()!.uppercased())
for character in message {
if let foundIndex = alphabet.index(where: {return $0 == character}) {
print(alphabet[(foundIndex + moveCount) % 26], terminator: "")
} else {
print(character, terminator: "")
}
}
실행 결과는...
I love Swift.
N QTAJ XBNKY.
파이썬입니다. 딕셔너리기능이 가장 깔끔한 것 같은데요. 띄어쓰기나 숫자,특수기호는 안바뀌고 대문자,소문자만 바뀌도록 했습니다.
data = input('Please enter the msg. : ')
n = int(input('Please enter the KEY number n : ')) % 26 ## 26 보다 큰 수 입력 가능하도록 설정
def caeser(data, n): ### 문제에서 요구한 암호화시켜주는 함수
a_to_z = 'abcdefghijklmnopqrstuvwxyz'
alpha = list(a_to_z * 2 + a_to_z.upper() * 2)
dic = {ord(alpha[i]): alpha[i+n] for i in list(range(26)) + list(range(52, 78))}
return data.translate(dic)
def caeser_translate(data, n): ### 암호화된 문장을 다시 해독해주는 함수
return caeser(data, 26-n)
print(data)
print(caeser(data, n))
print(caeser_translate(caeser(data, n), n)) ### 이 값은 print(data) 와 같게 나옵니다.(암호화 후 다시 해독했으므로)
python 3 입니다. 예외사항 생략
import string
args = input("input salt and word\n")
param = args.split(" ")
def encrypt(salt, target):
enc_word = ''
word = [w for w in string.ascii_uppercase]
for c in target:
enc_word += word[word.index(c) + int(salt)]
return enc_word
print(encrypt(param[0], param[1]))
import string
_input = list(input("Enter something to encrypt: "))
n = int(input("Number: "))
alphabet_lower = list(string.ascii_lowercase)
alphabet_upper = list(string.ascii_uppercase)
result = ''
for i, v in enumerate(_input):
if v in alphabet_lower:
index = (alphabet_lower.index(v) + n) % 26
_input[i] = alphabet_lower[index]
elif v in alphabet_upper:
index = (alphabet_upper.index(v) + n) % 26
_input[i] = alphabet_upper[index]
else:
pass
result = result.join(_input)
print(result)
Enter something to encrypt: COME TO ROME.
Number: 3
Result: FRPH WR URPH.
파이썬으로 작성했습니다.
def a(s,n):
mystr=''
for s1 in s:
mystr+=chr(ord(s1)+n)
print(mystr)
s=input('')
n=int(input(''))
a(s,n)
import java.util.Scanner; // 자바입니다
class Avg { String caesar(String s, int n) { String result = ""; String[] str = s.split(" "); StringBuffer sb = new StringBuffer(); for (int i=0; i<str.length; i++) { sb.append(str[i]); } char[] ch = sb.toString().toCharArray();
for (int j=0; j<n; j++) { // 각 숫자에 n번 만큼 1씩 더해준다
for (int i=0; i<ch.length; i++) {
ch[i]++;
if(ch[i] == 91) { // 그러다 대문자는 Z를 넘어서 Z+1이 되면 다시 A로
ch[i] = 65;
}
if(ch[i] == 123) {// 소문자는 z를 넘어서 z+1이 되면 다시 a로
ch[i] = 97;
}
}
}
sb.setLength(0);
for (int i=0; i<ch.length; i++) {
sb.append(ch[i]).append(" ");
}
result = sb.toString().trim();
return result;
}
public static void main(String[] args) {
Avg c = new Avg();
Scanner s = new Scanner(System.in);
System.out.println("s는 'a B z', n은 4인 경우: " + c.caesar(s.nextLine(), 4));
}
}
import java.util.Scanner;
public class hello {
public static void main(String[] args) {
String A="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String ans="";
int adress;
Scanner s= new Scanner(System.in);
System.out.println("문자열 입력 : ");
String word=s.nextLine();
System.out.println("n을 입력 :");
int n=s.nextInt();
n=n%26;
for(int i=0;i<word.length();i++) {
String cnt=word.substring(i,i+1);
if(cnt.equals(" ")) {
ans=ans+" ";
continue;
}
adress=A.indexOf(cnt);
ans=ans+A.substring(adress+n,adress+(n+1));
}
System.out.println(ans);
}
}
#include<stdio.h>
int main()
{
char name[100];
int count = 0;
int i = 0;
int n;
printf("단어를 입력하시오>>");
scanf("%s", &name);
printf("숫자를 입력하시오>>");
scanf("%d", &n);
while (name[i] != '\0')
{
i++;
count++;
}
for (int i = 0; i < count; i++)
{
printf("%c", name[i]+n);
}
printf("\n");
}
#include<iostream>
#include"stdafx.h"
int main()
{
string str;
int n;
cout << "Input_string:";
getline(cin,str);
cout << "Input_integer:";
cin >> n;
for (string::size_type i = 0; i < str.length(); i++)
{
if (str[i]>=97&&str[i]<=122)
{
if (str[i] + (n % 25)>122)
str[i] = (str[i] + (n % 25)-25);
else
str[i] = str[i] + (n % 25);
}
else
continue;
}
cout << "change_string:" << str << endl;
}
소문자만 처리했습니다. 대문자 하실분은 구문하나만 추가하시면됩니다.
s = input("문장을 입력하세요: ")
n = int(input("숫자를 입력하세요 : "))
result = ""
alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for i in s:
idx = alpha.find(i)
idx += n
result += alpha[idx]
print(result)
def my_func(a,n):
alphabet ='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for i in range(len(a)):
idx = alphabet.index(a[i])
if idx+n>len(alphabet):
return('ERROR')
print(alphabet[idx+n], end='')
my_func('CAT',5)
Python
test = ["CAT"]
for t in test:
ans = ""
for c in t:
if 65 <= ord(c) <= 90:
ans += chr((ord(c)-65)%26 + 70)
else:
ans += c
print(ans)
#word, n, AZ = input("word: ") , input("n: "), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
word, n, AZ = "CAT", 5 , 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
# 1. 배열을 이용한 방법
print(''.join([AZ[(AZ.find(c) + n)%26] for c in word]))
# 2. ASCII 값을 이용한 방법
str2 = ''
for c in word:
if 91 > ord(c): str2 += chr(ord(c) + n)
else: str2 +=chr((ord(c) + n)% 90 + 65)
print(str2)
dict = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
password = input("암호화할 문장은?")
n = int(input("암호를 만들 숫자는?"))
encoding = ""
for i in range(len(password)):
locate = dict.find(password[i])
encoding += dict[locate+n]
print("암호화된 문장은 = {}".format(encoding))
Python 3.6
def caesar_code(txt, n):
return ''.join(map(lambda i : chr((ord(i)-65+n)%26+65) if i.isupper() else chr((ord(i)-97+n)%26+97) if i.islower() else i, (x for x in txt)))
txt = 'Hello World! :)'
print( '원본: {}\n코드: {}'.format(txt, caesar_code(txt,3)) )
# 원본: Hello World! :)
# 코드: Khoor Zruog! :)
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
input_word = input("단어를 입력하세요 : ")
span = int(input("n값을 입력하세요 : "))
change = []
for x in input_word:
if x.isalpha():
index = alpha.find(x)
index += span
change.append(alpha[index])
result = "".join(change)
print(result)
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int A = 'A'; // 아스키코드- A: 65, Z: 90 ,, a: 97, z: 122 ,, 0: 48, 9: 57
Scanner sc = new Scanner(System.in);
String word = sc.next();
int n = sc.nextInt();
getWord(word, n);
}
public static void getWord(String st, int n)
{
String str = "";
for(int i = 0; i < st.length(); i++)
{
int k = st.charAt(i) - 65;
int l = (k + n) % 26;
str += (char)(l + 65);
}
System.out.println(str);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try {
System.out.println("문장을 입력해 주세요");
String st = new Scanner(System.in).nextLine();
System.out.println("암호 규칙을 입력해 주세요(숫자)");
int n = new Scanner(System.in).nextInt();
String result = "";
for(int i = 0; i < st.length(); i++){
result += (char)(st.charAt(i) + n);
}
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
code = input("암호를 입력하세요 : ")
for i in code:
askCode = ord(i)
temp = askCode + 3
anwser = chr(temp)
print(anwser, end='')
#include<stdio.h>
#include<string.h>
int main()
{
char name[10];
int i;
int cn = 0;
char a = 'Z';
printf("---시저 암호 풀기---\n바꾸려는 단어를 입력하세요 : ");
scanf("%s", name);
printf("\n알파벳 n개 만큼 뒤에 오는 알파벳으로 출력합니다 n을 입력하세요 : ");
scanf("%d", &cn);
for(i=0; i<strlen(name); i++)
{
if(cn>0 &&(name[i]=='z' || name[i]=='Z'))
{
name[i] = (name[i] - 25);
}
else
{
name[i] = name[i]+cn;
}
}
printf("%s", name);
printf("\n");
}
data = input('문자 입력:')
n = int(input('n입력 :'))
result=''
for i in data:
result+=chr(ord(i)+n)
print(result)
def code(word,n):
newW = ""
for c in word : newW += chr(ord(c)+n)
print(newW)
파이썬이고, 아스키 코드 변형을 이용했습니다.
package test;
public class test {
public static void main(String[] args) {
char[] str = "CAT".toCharArray();
int n = 3;
for (int i = 0; i < str.length; i++)
if (str[i] > 64 && str[i] < 91)
System.out.print((char) (str[i] + n > 90 ? str[i] + n - 26 : str[i] + n));
}
}
a=list(input())
n=int(input())
for x in range(len(a)):
a[x]=ord(a[x])+n
for y in a:
print(chr(y),end='')
s = input()
n = int(input())
print(''.join((chr((ord(x) - 64 + n) % 26 + 64) if x.isalpha() else x) for x in s)
음수 양수 대문자 소문자 포함
// =======================================
String st = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
st = st.replaceAll("[^a-zA-Z]", "");
String[] st1 = st.split("");
int num = 5;
for (int i = 0; i < st1.length; i++) {
if (st1[i].hashCode() >= 'A' && st1[i].hashCode() <= 'Z') {
if (num < 0) {
System.out.print((char) (st1[i].hashCode() + num + (st1[i].hashCode() + num < 'A' ? 26 : 0))); // 3 항연산자
} else {
System.out.print((char) (st1[i].hashCode() + num + (st1[i].hashCode() + num > 'Z' ? -26 : 0)));
}
} else if (st1[i].hashCode() >= 'a' && st1[i].hashCode() <= 'z') {
if (num < 0) {
if (st1[i].hashCode() + num < 'a') { // 일반 if문
System.out.print((char) (st1[i].hashCode() + num + 26)); //
} else { //
System.out.print((char) (st1[i].hashCode() + num)); //
} //
} else {
if (st1[i].hashCode() + num > 'z') {
System.out.print((char) (st1[i].hashCode() + num - 26));
} else {
System.out.print((char) (st1[i].hashCode() + num));
}
}
}
}
str_arr=str(input("문자열을 입력하시오:"))
num=int(input("숫자를 입력하시오:"))
str_list=[]
for x in range(0,len(str_arr)):
for k in range(65,91):
if str_arr[x]==chr(k):
str_list.append(chr(k+num))
print("".join(str_list))
passward = list(input()) #BCE
key = int(input()) #2
decipher = ''
for char in passward:
alpha = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
if char in alpha:
if (alpha.index(char) + key) >= len(alpha):
decipher += alpha.pop((alpha.index(char) + key) - len(alpha))
else:
decipher += alpha.pop(alpha.index(char) + key) # B의 인덱스 1 + 2
else:
decipher += char
print(decipher)
```{.python}
```# 시저 암호 만들기
def ceasor_code(ceasor,n) :
ceasor_list = list(ceasor)
alphabet_list = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'
box = []
for i in ceasor_list :
if i in alphabet_list :
i = alphabet_list[alphabet_list.find(i) + (n % 26)]
box.append(i)
else :
i = ' '
box.append(i)
code = ''.join(box)
print(code)
ceasor = ceasor_code(input(" 영어 문장 입력 : "), int(input(" 자연수 입력 : ")))
package pac;
import java.util.*;
public class franklin {
public static void main(String[] args)
{
Scanner scanf = new Scanner(System.in);
String s;
char c;
int ascii_conversion;
int n=0x03;
System.out.print("Put your word: ");
s = scanf.nextLine();
for(int i=0;i<s.length();i++)
{
c = s.charAt(i);
if(c != (char)0x20 && c != (char)0x3F &&c != (char)0x21 && c != (char)0x2E && c != (char)0x2C)
{
ascii_conversion = (int)c+n;
System.out.print((char)ascii_conversion);
}
else
{
System.out.print(c);
}
}
}
}
느낌표, 쉼표, 온점, 물음표, 띄어쓰기 만 빼고 변경하도록 만들어보았습니다...
[예시] Put your word: Hello? It is me! Mario!
Khoor? Lw lv ph! Pdulr!
import java.util.Scanner;
public class KimSanghyeop {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("문장을 입력하세요 :" );
String str = sc.nextLine();
System.out.println("건너뛸 N을 입력하세요.");
int n1 = sc.nextInt();
String res= "";
for(int f1=0;f1<str.length();f1++)
{
res = res + (char)(str.charAt(f1) +n1);
//System.out.println(res);
}
System.out.println(res);
}
}
# Caesar_cipher.py
str_inp = input("Enter your sentence : ")
num_inp = int(input("Enter your number : "))
str_out = ''
for c in str_inp:
if c.islower():
num = (ord(c) + num_inp - ord('a'))%26 + ord('a')
elif c.isupper():
num = (ord(c) + num_inp -ord('A')) % 26 + ord('A')
else:
num = ord(c)
str_out = str_out+chr(num)
print(str_out)
Enter your sentence : CAT Z cat z
Enter your number : 5
HFY E hfy e
#include<stdio.h>
#include<string.h>
int main(void)
{
char a[100]="";
int n,i;
printf("문자열을 입력하세요:");
scanf_s("%s", &a, sizeof(char) * 100);
printf("숫자를 입력하세요:");
scanf_s("%d", &n);
int p = strlen(a);
for (i = 0; i < p; i++)
{
if (a[i] >= 'A'&&a[i] <= 'Z')
{
if (a[i] + n > 90)
a[i] = a[i] - (26 - n);
else
a[i] = a[i] + n;
}
else
{
if (a[i] + n > 122)
a[i] = a[i] - (26 - n);
else
a[i] = a[i] + n;
}
}
printf("%s", a);
return;
}
word = list(input())
n = int(input())
wordbag='ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ'
def password(word,n):
temp = []
for i in word:
ind = wordbag.find(i)
temp.append(wordbag[ind+n])
return ''.join(temp)
print(password(word,n))
function ciger(input, n){
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
let result = ''
for(let i = 0; i<input.length; i++){
for(let j = 0; j<26; j++){
if(j<21 && input[i]===alphabet[j]){
result+=alphabet[j+n]
}else if(j>=21&& input[i]===alphabet[j]){
result+=alphabet[j-21]
}
}
}
return result
}
ciger('CAT', 5)
//출력: 'HFY'
ciger('CAZ', 5)
//출력: 'HFE'
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
in_str = 'CAT'
out_str = ''
n = 5
length = len(alphabet)
for i in range(len(in_str)):
idx = alphabet.find(in_str[i])
tgt_idx = 0
if idx + n >= length:
tgt_idx = length - (idx + n)
else:
tgt_idx = idx + n
out_str += alphabet[tgt_idx]
print(out_str)
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def Caesar_code(a, n):
result = ''
for i in range(len(a)):
p = alphabet.find(a[i])
result += alphabet[p + n]
result.join(', ')
return result
print(Caesar_code('CAT', 5))
import java.util.Scanner;
public class Problem138 {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
String str;
System.out.println("바꾸려는 단어 : ");
str = scan.nextLine();
int n;
System.out.println("n 값 : ");
n = scan.nextInt()%26;
scan.close();
char[] strarray = new char[str.length()];
for(int i=0;i<str.length();i++) {
strarray[i]=(str.charAt(i));
if(Character.isLowerCase(strarray[i])==true) {
if(strarray[i]+n>122)
strarray[i]=(char)(strarray[i]+n-26);
else
strarray[i]+=n;
}
if(Character.isUpperCase(strarray[i])==true) {
if(strarray[i]+n>90)
strarray[i]=(char)(strarray[i]+n-26);
else
strarray[i]+=n;
}
}
System.out.println(strarray);
}
}
namespace codingdojang__
{
class Program
{
static void Main(string[] args)
{
Caesar("CAT", 5);
}
static void Caesar(string input, int n)
{
List<int> ascii = new List<int> { };
int num = n % 26;
for (int i = 0; i < input.Length; i++)
{
ascii.Add(Convert.ToInt32(input[i]) + num);
}
foreach(var i in ascii)
{
Console.Write(Convert.ToChar(i));
}
Console.WriteLine();
}
}
}
alp='abcdefghijklmnopqrstuvwxyz'
ALP='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
while True:
user=input("Input sentence: ")
n=int(input("Input n: "))
password=''
for i in range(len(user)):
if user[i] in alp:
password=password+alp[(alp.index(user[i])+n)%26]
elif user[i] in ALP:
password=password+ALP[(ALP.index(user[i])+n)%26]
else:
password=password+user[i]
print(password)
비쥬얼 스튜디오 2017 C++로 작성했습니다. 반복문과 배열을 이용했네요
#include <stdio.h>
#include <iostream>
using namespace std;
void main() {
char array[20], result[20];
int n;
printf("문장과 n을 입력하세요 :");
scanf("%s %d", array, &n);
for (int i = 0; i < strlen(array); i++)
{
result[i] = array[i] + n ;
printf("%c", result[i]);
}
}
package level1;
public class sizer {
public static void main(String[] args) {
String input = "CAT";
sizerFunction(input, 5);
}
static void sizerFunction(String input, int number){
for(int i=0; i<input.length(); i++){
char a = (char) ((byte)input.charAt(i) + number);
System.out.print(a);
}
}
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 100
void caesar(int n, char str[]){
int i=0;
for(i=0;i<SIZE;i++){
if(str[i]>=65&&str[i]<=90){
str[i]=(str[i]-65+n)%26+65;
}
else if(str[i]>=97&&str[i]<=122){
str[i]=(str[i]-97+n)%26+97;
}
}
}
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
char str[SIZE]; int n;
printf("input n: ");
scanf("%d",&n);
fflush(stdin);
printf("input string: ");
fgets(str,SIZE,stdin);
caesar(n,str);
printf("converted string: %s",str);
return 0;
}
``````{.cpp}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 100
void caesar(int n, char str[]){
int i=0;
for(i=0;i<SIZE;i++){
if(str[i]>=65&&str[i]<=90){
str[i]=(str[i]-65+n)%26+65;
}
else if(str[i]>=97&&str[i]<=122){
str[i]=(str[i]-97+n)%26+97;
}
}
}
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
char str[SIZE]; int n;
printf("input n: ");
scanf("%d",&n);
fflush(stdin);
printf("input string: ");
fgets(str,SIZE,stdin);
caesar(n,str);
printf("converted string: %s",str);
return 0;
}
def casor(inputdata,n):
inputdata.lower()
res = ""
for c in inputdata:
myord = int(ord(c))
if 122-n-1 <= myord <= 122:
res += (chr(myord-26+n))
else :
res += (chr(myord+n))
return res
inputdata = str(input("입력: "))
n = int(input("숫자: "))
print(casor(inputdata,n))
m= int(input());n=m%26
s=input();ans=''
for i in s:
if ord(i)<=ord('Z') and ord(i)+n > ord('Z'):
ans+=chr(ord('A')+(ord(i)+n)%ord('Z')-1)
elif ord(i)>ord('Z') and ord(i)+n > ord('z'):
ans+=chr(ord('a')+(ord(i)+n)%ord('z')-1)
else:
ans+=chr(ord(i)+n)
print(ans)
카이사르의 암호에 대해서 잘 모르기에, 만약 n=54513 처럼 암호문 변환 시 'z'나 'Z'를 넘어가는 경우, 각각 'a'와'A'로 순환하여 계속 일순 할 수 있도록 하여 보았읍니다.
def 시저(b, n):
a= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for i in b:
c=a.find(i)+n
if c >= len(a):
print(a[c-len(a)], end='')
else: print(a[c], end='')
시저('CAT', 5)
words = input("Enter word: "); n = int(input("Enter number: "))
for i in words:
print("%c" % (int(ord(i))+n), end='')
def caesar(str, num):
word = str
result = []
for i in word:
order = ord(i)
result.append(chr(order + num))
return result
print(*caesar('cat', 5), sep='')
data = input('문장을 입력해주세요 : ')
n = int(input('n : '))
caesar = ''
for i in range(len(data)):
char = data[i]
char_num = ord(char)
if char.islower():
char_num = (char_num + n - ord('a')) % 26 + ord('a')
elif char.isupper():
char_num = (char_num + n - ord('A')) % 26 + ord('A')
caesar += chr(char_num)
print(data, '--->', caesar)
_o = [ord('a'), ord('A')]
f_o = lambda c: _o[c.isupper()]
while __name__ == '__main__':
n = int(input('''N<<<'''))
s = input('''STRING<<<''')
print(''.join(chr(f_o(c)+(ord(c)-f_o(c)+n)%26)\
if not c.isnumeric() else c for c in s))
파이썬 3.7.3
def ceaser(text,n):
t = list(text)
for i in range(len(t)):
# 대문자이면서 n을 더하였을때 Z를 넘어가는 경우
if t[i].isupper() and ord(t[i]) + n > 90:
t[i] = chr(ord(t[i]) + n - 26)
# 소문자이면서 n을 더하였을때 z를 넘어가는 경우
elif t[i].islower() and ord(t[i]) + n > 122:
t[i] = chr(ord(t[i]) + n - 26)
else:
t[i] = chr(ord(t[i]) + n)
return t
print(ceaser('asdfz',3))
a=input("암호를 만들 문장 입력")
n=int(input("숫자입력:"))
b=""
for i in a:
if (ord(i)>=65 and ord(i)<=85) or (ord(i)>=97 and ord(i)<=117):
b=b+chr(ord(i)+n)
elif (ord(i)>85 and ord(i)<=90):
b=b+chr(ord('A')+(n-(90+1-ord(i))))
elif (ord(i)>117 and ord(i)<=122):
b=b+chr(ord('a')+(n-(122+1-ord(i))))
else:
b=b+i
print(b)
# Algorithm
def Transform(t_num, word):
a_word = []
for i in range(len(word)):
t = chr(ord(word[i]) + t_num) # transfer by t_num
a_word.append(t) # append word that transfer
return ''.join(a_word) # return string
# Input argument
t_num = int(input()); word = list(input())
print(Transform(t_num, word)) # call function
public class CeaserPw {
public static String ceaserCode(String str, int n) {
char[] chrArr = str.toCharArray();
for(int i=0; i<chrArr.length; i++) {
chrArr[i] = (char) (chrArr[i] + n);
}
String string = new String(chrArr);
return string;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print(">> 알파벳 입력 : ");
String str = sc.nextLine();
System.out.print(">> n 입력 : ");
int n = Integer.parseInt(sc.nextLine());
str = ceaserCode(str, n);
System.out.println(str);
sc.close();
}// end of main()------------------------------------------------
}
java : char type에 사칙연산을 한 후 다시 char로 casting했습니다.
pw = 'abcdefghijklmnopqrstuvwxyz'
pw_list = list(pw)
temp =[]
def password(text, n):
for i in range(len(text)):
for j in range(len(pw)):
if text[i] == pw[j]:
if j+n > 26:
temp.append(pw[j+n-26])
else :
temp.append(pw[j+n])
print("".join(temp))
password("catz",5)
a = input("알파벳을 입력하시오 : ")
n = input("n의 수를 입력하시오 : ")
d = ""
for i in a:
c = ord(i)+int(n)
d += chr(c)
print(d)
파이썬
# Caesar's secret code
s = input("Input a sentence to generate a secret code: ")
num = int(input("Input a secret number: "))
num = num % 26
result = ""
for i in range(len(s)):
i2 = ord(s[i]) + num
if ord(s[i]) < 91:
if i2 > 90:
i2 -= 26
else:
if i2 > 122:
i2 -= 26
result += chr(i2)
print(result)
alpha = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n',\
'o','p','q','r','s','t','u','v','w','x','y','z']
Alpha = []
for i in alpha:
a=i
Alpha.append(a.upper())
text = input("문장을 입력하시오(대문자로):")
n = int(input("number:"))
text_list = list(','.join(text))
new_text_list = []
for i in text_list:
if i != ' ' and i != ',':
index_number = int(Alpha.index(i))
if index_number <= len(Alpha)-1-n: # 리스트 맨끝의 index는 len-1 이라서
new_text_list.append(Alpha[index_number+n])
elif index_number > len(Alpha)-1-n:
index_number = (index_number+n)%len(Alpha)
new_text_list.append(Alpha[index_number])
elif i == ',':
pass
else:
b = i
new_text_list.append(b)
for i in new_text_list:
print(i, end='')
컴퓨터 언어 처음 배운지 9일째라 허접하지만 용기내 봅니다.
package CodingDojang;
import java.util.Scanner;
public class CaesarPassQuiz {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String ans = scanner.nextLine();
int n = scanner.nextInt();
String result = "";
for(int i = 0; i < ans.length(); i++) {
if(ans.charAt(i) == ' ') result += ans.charAt(i);
else {
int tmp = 0;
int count = 0;
int check = ans.charAt(i);
if(check >= 65 && check <= 90) {
tmp = (ans.charAt(i) + n);
count = (ans.charAt(i) + n) % 90;
if(tmp > 90) tmp = 64 + count;
}
else if(check >= 97 && check <= 122){
tmp = (ans.charAt(i) + n);
count = (ans.charAt(i) + n) % 122;
if(tmp > 122) tmp = 96 + count;
}
result += (char)tmp;
}
}
System.out.println(result);
}
}
대문자 Z와 소문자 z를 초과 하였을때 다시 A 또는 a로 복귀 하도록 처리 하였습니다.
import java.util.*;
public class 시저암호풀기 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String line = scan.nextLine();
int num = scan.nextInt();
char[] line_char = line.toCharArray();
for(int i=0; i<line_char.length; i++) {
line_char[i]+=num;
}
System.out.println(line_char);
}
}
//공백도 바뀜..........
파이썬 입니다. 암호화 입니다.
import string
crypto_ref = list(string.ascii_uppercase) # 알파벳 대문자만 오도록 string을 import 후 리스트 작성 (일일이 다 치지않음)
def secret(string,n): # 변환할 단어 or 문장(string) / 몇칸 건너뛸지 (n) 을 입력 받게 함수 설정
a=list(string) # 입력받은 string을 list로 만든다.
crypted=[] # 변환한 단어를 담을 리스트를 정의
for i in a: # 변활할 알파벳을 순차적으로 꺼낼 for 문을 작성
b=crypto_ref.index(i) # 변환할 알파벳이 crypto_ref에서 몇번째 인덱스에 있는지 인덱스를 찾는다.
crypted.append(crypto_ref[int((b+n)%26)]) # 찾은 index, b에 n을 더하고 26으로 나눈 나머지를 인덱스로하여
return ''.join(crypted) # crypto_ref에서 알파벳을 적용 후 crypted 리스트에 담는다.
# join() 함수를 이용하여 리스트에 담긴 알파벳들을 하나로 합친다.
secret('RETURNTOBASE',9) # 결과값 : 'ANCDAWCXKJBN'
공백제거하는 while 문 추가
import string
crypto_ref = list(string.ascii_uppercase)
def secret(string,n):
a=list(string)
while True: # 공백 제거하는 while 문을 추가 했습니다.
if ' ' in a: # ' '(공백)이 list a에 포함되면
a.remove(' ') # 제거
else:
break # 공백 전부 제거시 while 문을 빠져나온다.
crypted=[]
for i in a:
b=crypto_ref.index(i)
crypted.append(crypto_ref[int((b+n)%26)])
return ''.join(crypted)
secret('NIKE',5)
import string
alphalist = list(string.ascii_uppercase)
def caesar(word, num):
result = []
wordlist = list(word.upper())
for w in wordlist:
index = alphalist.index(w)
result.append(alphalist[index + num])
return ''.join(result)
print(caesar('CAT', 5))
print(caesar('ABCDEFG', 1))
파이썬입니다. 뭔가 비효율적인...
import string
x = input('암호를 입력하시오')
n = int(input('숫자를 입력하시오'))
for i in range(len(x)):
print(string.ascii_letters[string.ascii_letters.find(x[i])+n], end='')
az='ABCDEFGHIGKLMNOPQRSTUVWXYZ'
a=[]
def sizer(word,n):
for i in range(0,len(word)):
p =az.find(word[i])
a.append(az[(p+n)%26])
return a
word=input("영문입력:")
print(sizer(word,5))
print(len(az))
a=input("알파벳 문자열을 입력하십시오: ")
n=int(input("양의 정수 n을 입력하십시오: "))
alpha=list("abcdefghijklmnopqrstuvwxyz"*10) # n에 엄청 큰 수를 대입했을 때 index out of range를 피하기위해 알파벳을 10번 반복한 리스트 생성
dw=""
for k in a:
if k in alpha:
k=alpha[alpha.index(k)+n]
dw+=k
print(dw)
alf_list = ([a for a in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.lower()])
stringStr = 'cat'
num = 5
for s in stringStr:
if s in alf_list:
print(alf_list[alf_list.index(s) + num])
n = int(input("n을 입력하세요:"))
word = input("문장입력:")
word = list(word)
for w in word:
words = ord(w) + n
print(chr(words), end='')
pre_defined = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # 안하는 방법은? 아스키코드로 어차피 이어져있으니 그 범위 내에서 + 하는 식으로. 근데 범위 넘어갈 경우도 생각해야.
inputstring,result = input("알파벳 3개를 입력하시오 : "), [] # "CAT" # z일때 e = -21 x일때 c. v가 임계점인데 a가 된다.
inputint = input("암호인자(숫자)를 입력하시오 : ") # "5"
for i in inputstring:
tmp = pre_defined.find(i)
if int(tmp) <= 21 : # 그냥 임계점을 찾아서 if문으로 조짐
result.append(pre_defined[tmp+int(inputint)])
else :
result.append(pre_defined[tmp-(26-int(inputint))])
print("".join(result))
a = list(input("문자를 입력: "))
b = int(input("수를 입력: "))
c = list("abcdefghijklmnopqrstuvwxyz")
d = []
for i in a:
x = c.index(i)+b
if x > 26:
x = x-26
y = c[x]
d.append(y)
print("".join(d))
import java.util.Scanner;
public class Encryption {
public static void main(String[] args) {
Scanner Sc = new Scanner(System.in);
Encryption Ec = new Encryption();
System.out.print("문장을 입력하시오: ");
String str = Sc.nextLine();
System.out.print("숫자를 입력하시오: ");
int num = Sc.nextInt();
Ec.arrayConvert(str,num);
Sc.close();
}
void arrayConvert(String s, int n) {
char[] array = s.toCharArray();
int[] intArray = new int[array.length];
for(int i=0; i< array.length; i++) {
if(array[i]>=65 && array[i]<= 90) { //대문자일 경우, Z를 넘어가면 A부터 다시 시작
intArray[i]= ((int) array[i]) + n;
if(intArray[i]>90) {
intArray[i] -= 25;
}
array[i] = (char) intArray[i];
}
else if(array[i]>=97 && array[i]<= 122) { //소문자일 경우, z를 넘어가면 A부터 다시 시작
intArray[i]= ((int) array[i]) + n;
if(intArray[i]>122) {
intArray[i] -= 25;
}
array[i] = (char) intArray[i];
}
System.out.print(array[i]);
}
}
}
문장을 입력하시오: MY name is kangminKim.
숫자를 입력하시오: 5
RE sfrj nx pfslrnsPnr.
// 특수문자와 공백은 변환하지 않았습니다.
global alphabet
global word
alphabet = 'abcdefghijklmnopqrstuvwxyz'
word = input('Original Message: ')
code = []
def caesar(n):
for i in range(0, len(word))
a = alphabet.find(word[i])
code.append(alphabet[p + n])
return code
def caesar_pw(o,s,n):
if len(s) <=0 or n <0 :
return
lower="abcdefghijklmnopqrstuvwxyz"
upper="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
nsize = len(lower)
szip = str()
if o == 0: #암호화
for c in s:
if str(c).islower():
i = lower.find(c)
if i <=-1: #그밖의 특수문자
szip +=str(c)
continue
order = (n+i) % nsize
# print(i,'order', order)
szip += lower[order];
else:
i = upper.find(c)
if i <= -1 : #그밖의 특수문자
szip +=str(c)
continue
order = (n+i) % nsize
# print('order', order)
szip += upper[order];
elif o== 1: #복호화
for c in s:
if str(c).islower():
i = lower.find(c)
if i <=-1: #그밖의 특수문자
szip +=str(c)
continue
order = (i-n) % nsize
# print('i',i,'order', order)
szip += lower[order];
else:
i = upper.find(c)
if i <=-1: #그밖의 특수문자
szip +=str(c)
continue
order = (i-n) % nsize
# print('i',i,'order', order)
szip += upper[order];
print("input:",s,'=>',szip)
caesar_pw(0,"I'm smith", 5)
caesar_pw(1,"N'r xrnym", 5)
caesar_pw(0,"aCAT", 31)
caesar_pw(1,"fHFY", 31)
결과
input: I'm smith => N'r xrnym
input: N'r xrnym => I'm smith
input: aCAT => fHFY
input: fHFY => aCAT
a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
a_list = list(a)
w = input("Enter the word:")
w_list = list(w)
n = input("Enter the number:")
for i in range(0,len(w_list)):
print(a_list[a_list.index(str(w_list[i]))+5],end="")
a = input() #숫자 입력 b = input() #영어 단어 입력
result = [] for n in b: temp = ord(n) + int(a) result.append(chr(temp))
print("".join(result))
alphabet = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
cod,num = input("code"),(int(input("number")))
caesar = list(x for x in (cod.upper()))
result = []
for i in caesar:
k = alphabet.index(i)
result.append(alphabet[k+num])
for j in result:
print(str(j), end="")
def caesar_pass(apb, n):
list_a = []
result = ''
for x in apb:
list_a.append(x)
for y in range(0, len(list_a)):
list_a[y] = chr(ord(list_a[y]) + 5)
for z in list_a:
result += z
return result
case = 'CAT'
print(caesar_pass(case, 5))
# 시저 암호는, 고대 로마의 황제 줄리어스 시저가 만들어 낸 암호인데, 예를 들어 알파벳 A를 입력했을 때,
# 그 알파벳의 n개 뒤에 오는(여기서는 예를 들 때 3으로 지정하였다)알파벳이 출력되는 것이다.
# 예를 들어 바꾸려는 단어가 'CAT"고, n을 5로 지정하였을 때 "HFY"가 되는 것이다.
# 어떠한 암호를 만들 문장과 n을 입력했을 때 암호를 만들어 출력하는 프로그램을 작성해라.
# 아스키코드를 쓰자
def caesor(str, n):
result = ""
for i in str:
char_num = ord(i)
if i.islower():
char_num = (char_num - ord('a') + n) % 26 + ord('a')
elif i.isupper():
char_num = (char_num - ord('A') + n) % 26 + ord('A')
result += chr(char_num)
return print(result)
caesor("abcedasd", 500)
n=int(input('n='))
w=str(input('input words....'))
for i in range(len(w)):
if ord(w[i])>=65 and ord(w[i])<=90:
print (chr(((ord(w[i])+n-65)%26)+65),end='')
elif ord(w[i])>=97 and ord(w[i])<=122:
print (chr(((ord(w[i])+n-97)%26)+97),end='')
else:
print (w[i],end='')
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
public class Q138 {
public static void main(String[] args) {
String[] keyUpper = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
"L", "M", "N", "O", "P", "Q", "R","S", "T", "U", "V", "W", "X", "Y", "Z" };
String[] keyLower = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
"l", "m", "n", "o", "p", "q", "r","s", "t", "u", "v", "w", "x", "y", "z" };
HashMap<String, Integer> mapUpper = new HashMap<String, Integer>();
HashMap<String, Integer> mapLower = new HashMap<String, Integer>();
for (int i = 0; i < keyUpper.length; i++)
mapUpper.put(keyUpper[i], i);
for (int i = 0; i < keyLower.length; i++)
mapLower.put(keyLower[i], i);
Scanner scan = new Scanner(System.in);
System.out.print("Sentence : ");
String[] sent = scan.nextLine().split("");
System.out.print("Number : ");
int number = scan.nextInt();
ArrayList<String> pw = new ArrayList<String>();
for (int i = 0; i < sent.length; i++) {
if (mapUpper.containsKey(sent[i])) {
if (mapUpper.get(sent[i]) + number < keyUpper.length)
pw.add(keyUpper[mapUpper.get(sent[i]) + number]);
else if (mapUpper.get(sent[i]) + number >= keyUpper.length)
pw.add(keyUpper[mapUpper.get(sent[i]) + number - keyUpper.length]);
} else if (mapLower.containsKey(sent[i])) {
if (mapLower.get(sent[i]) + number < keyLower.length)
pw.add(keyLower[mapLower.get(sent[i]) + number]);
else if (mapLower.get(sent[i]) + number >= keyLower.length)
pw.add(keyLower[mapLower.get(sent[i]) + number - keyLower.length]);
} else
pw.add(sent[i]);
}
System.out.print("Password : ");
for (int i = 0; i < pw.size(); i++)
System.out.print(pw.get(i));
scan.close();
}
}
key = input()
str = input()
result = ""
for n in str:
temp = ord(n) + (int)(key)
result = result + chr(temp)
print(result)
두시간동안 헤매다가 답변들보고 내장함수를 발견했네요ㅠㅠㅠ
string=(":".join(input("문장을 지정하세요"))).split(":")
n=int(input("n:"))
x=""
for i in string:
if ord(i)>=65 and ord(i)<=90:
oord=ord(i)+n
if oord>90:
x=x+chr(65+(oord-91)%26)
else:
x=x+chr(oord)
elif ord(i)>=97 and ord(i)<=122:
oord1 = ord(i) + n
if oord1 > 122:
x = x + chr(97 + (oord1 - 123) % 26)
else:
x = x + chr(oord1)
else:
x=x+i
print(x)
Nlist = list(input())
Nint = int(input())
M = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
for i in range(len(Nlist)):
check = ''
for j in range(len(M)):
if Nlist[i] == M[j]:
if len(M) - 1 >= (j+Nint):
check = M[j+Nint]
elif len(M) - 1 < (j + Nint):
check = M[(j + Nint) -len(M)]
print(check,end="")
def f(s, n):
char = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
tmp =""
for c in s:
num = char.index(c)
num = (num + n) % len(char)
tmp += char[num]
return tmp
#시저 암호 풀기
input_str = input("문장을 입력하세요 : ")
input_no = int(input("숫자를 입력하세요 : "))
temp=[]
print(input_str)
print(input_no)
for i in range(0,len(input_str)) :
temp.append(chr(ord(input_str[i])+input_no))
print(temp[i],end='')
파이썬을 사용했습니다.
#138 시저암호풀기
lowercase = "abcdefghijklmnopqrstuvwxyz"
uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
after_word_list = []
# 사용자가 자연수 n이외의 다른 값을 입력하지 못하도록 만들었습니다.
while True:
number = input("자연수 n의 값을 입력하시오:")
try:
n = int(number)
if n <= 0:
print("오류입니다. 자연수 n의 값을 입력하시오.")
continue
else:
break
except ValueError:
print("오류입니다. 자연수 n의 값을 입력하시오")
continue
# 문장을 검사하는 함수를 만들었습니다. 알파벳과 공백 이외의 문자가 들어가있으면 True 값을 반환합니다.
def sentence_check(test_sentence):
for alphabet in test_sentence:
if alphabet not in list(lowercase)+list(uppercase)+[" "]:
print("문장에 알파벳 이외에 다른 문자가 들어가있습니다. 다시 입력하세요")
return True
else:
return False
# 알파벳과 공백으로만 이루어진 문장이 입력된다면 다음 단계로 넘어가도록 설정하였습니다.
while True:
sentence = input("알파벳으로만 이루어진 문장을 입력하시오:")
if sentence_check(sentence) == False:
break
position_number = 0
n = n % 26
for before_word in sentence:
if before_word == " ":
after_word_list.append(before_word)
elif before_word in lowercase:
for x in lowercase:
if x == before_word:
break
else:
position_number += 1
position_number = position_number + n
position_number = position_number % 26
after_word = lowercase[position_number]
after_word_list.append(after_word)
position_number = 0
elif before_word in uppercase:
for x in uppercase:
if x == before_word:
break
else:
position_number += 1
position_number = position_number + n
position_number = position_number % 26
after_word = uppercase[position_number]
after_word_list.append(after_word)
position_number = 0
print("".join(after_word_list))
input_text, input_n = input("문장 : "), int(input("숫자 : "))
print("".join([" " if x == " " else chr(ord(x) + input_n) for x in input_text]))
파이썬입니다
namespace _60일차_9월30일
{
class MainApp
{
static void Main(string[] args)
{
// 'CAT"고, n을 5로 지정하였을 때 "HFY"가 되는 것이다.
Console.Write("암호화할 단어 입력 : ");
string Input = Console.ReadLine();
Console.Write("알파벳 순서 + 넘버 : ");
string Input_Number = Console.ReadLine();
List<char> result = new List<char>();
char[] Data = Input.ToCharArray();
for (int i = 0; i < Data.Length; i++)
{
int Convert_Data = Data[i] + int.Parse(Input_Number);
result.Add(Convert.ToChar(Convert_Data));
}
foreach(var Convert in result)
{
Console.Write(Convert);
}
}
}
}
public static String rome(int number) {
Scanner sc = new Scanner(System.in);
System.out.print("단어:");
String voca = sc.next().toUpperCase();
for(int i=0; i < voca.length(); i++) {
voca = voca.replace(voca.charAt(i), (char)(voca.charAt(i)+number));
}
return voca;
}
word=map(str, input().upper())
n=int(input())
alpha='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
n_word=''
for i in word:
if i in alpha:
a=alpha.find(i)+n
n_word+=alpha[a]
else:
n_word+=str(i)
print(n_word)
class CodeBreaker:
def __init__(self):
self.line = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # from 0 to 25
def encode(self,input,jump):
output = ""
for i,n in enumerate(input):
if input[i] == " ":
output += " "
else:
for j,m in enumerate(self.line):
if input[i]==self.line[j]:
nn = j+jump
if nn>25:
nn = jump-26+j
output += self.line[nn]
print(output)
def decode(self,output,jump):
input = ""
for i,n in enumerate(output):
if output[i] == " ":
input += " "
else:
for j,m in enumerate(self.line):
if output[i]==self.line[j]:
nn = j-jump
if nn<0:
nn = 25-(j-jump)*(-1)+1
input += self.line[nn]
print(input)
a = CodeBreaker()
a.encode("A B C D E F G H I J K L M N O P Q R S T U V W X Y Z",5)
a.decode("F G H I J K L M N O P Q R S T U V W X Y Z A B C D E",5)
def en(passwd,shift):
result=''
shift=shift%26
for i in passwd:
if ord(i)<=90 and ord(i)>=65:
if ord(i)+shift>90:
result=result+chr(ord(i)+shift-26)
elif ord(i)+shift<65:
result=result+chr(ord(i)+shift+26)
else:
result=result+chr(ord(i)+shift)
elif ord(i)>=97 and ord(i)<=122:
if ord(i)+shift>122:
result=result+chr(ord(i)+shift-26)
elif ord(i)+shift<97:
result=result+chr(ord(i)+shift+26)
else:
result=result+chr(ord(i)+shift)
else:
result=result+i
return result
n=int(input('How much should I shift?:'))
passwd=input('What should I encode?:')
passwd=en(passwd,n)
print(passwd)
def CESAR(text,n):
alpha = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
result = []
for i in text:
for j in alpha:
if j == i:
result.append(alpha[alpha.index(j)+n])
return "".join(result)
text = input('INPUT: ')
number = int(input('NUMBER: '))
print(CESAR(text,number))
abc = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z"
ABC = abc.split(",")
def caesar_code(inp,n):
result = ""
for i in range(len(inp)):
for k in ABC:
if inp[i] == k:
result += str(ABC[ABC.index(k)+n])
print(result)
caesar_code('CAT',5)
import string
def make_pass(step=3):
"""Take a user input(only alphabet) as a password.
Then change the user input(alphabet) a few steps behind the original position in alphabetic order.
In this case steps are 3.
for example given letter is "a" with a step 3, return "d".
Args:
step (int, optional): how many steps you would like to show behind input alphabet.
Defaults to 3.
Returns:
string type: return a string type of password.
"""
alphabet_string = string.ascii_lowercase
user_pass = " "
new_pass = ""
while not user_pass.isalpha():
user_pass = input("Type your sentence to make a password(only letter): ")
user_pass = user_pass.replace(" ", "")
for letter in user_pass:
alp_index = alphabet_string.index(letter)
step_alp_index = alp_index + step
if step_alp_index > 25:
step_alp_index = step_alp_index - 26
new_pass += alphabet_string[step_alp_index]
else:
new_pass += alphabet_string[step_alp_index]
return new_pass
result = make_pass(step=6)
print(result)
def Si_Password(word,n):
Big=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
Small=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
answer=[]
for i in word:
if i in Big:
answer.append(Big[(Big.index(i)+n)%26])
elif i in Small:
answer.append(Small[(Small.index(i)+n)%26])
else:
answer.append(i)
forprint="".join(answer)
print(forprint)
word=input("word :")
n=int(input("today password? :"))
Si_Password(word,n)
import java.util.Scanner;
public class sigger {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("암호화할 문자를 입력하시오.");
String a = sc.next();
System.out.println("암호 키값");
int k = sc.nextInt();
char[] re = new char[a.length()];
System.out.print("암호화된 문자 : ");
for(int i =0; i<a.length(); i++){
re[i] = (char)(int)(a.charAt(i) + k);
System.out.print(re[i]);
}
}
}
package main;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String pw = "";
pw = sc.next();
int n = 0;
n = sc.nextInt();
for (int i = 0; i < pw.length(); i++) {
System.out.print((char)(pw.charAt(i)+n));
}
}
}
n = int(input())
s = input().split()
for i in s:
for j in i:
if( (ord(j)>=ord("A") and ord(j) <= ord("Z")) and ord(j) + n > 90):
print(chr((ord(j) + n -ord("Z")) + (ord("A") - 1)), end = '')
elif((ord(j)>=ord("a") and ord(j) <= ord("z")) and ord(j) + n > 122):
print(chr((ord(j) + n -ord("z")) + (ord("a") - 1)), end = '')
else:
print(chr(ord(j) + n), end = '')
print(" ", end = '')
무식하게 풀어봤습니다... 어렵네영 코딩은
def chiper(text):
alpha='abcdefghijklmnopqrstuvwxyz'
result = ''.join([alpha[alpha.find(x)+5] if alpha.find(x)<=21 else alpha[alpha.find(x)-21] for x in text ])
return result
c = ["a","b","c","d",'e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] #알파벳 리스트 만들기
ab=[] #ab는 나중에 암호화된 리스트가 들어갈 공간
m = input("암호화 하고 싶은 문자 : ")
n = int(input("키값 : "))
while n>=26: # while문을 사용해서 n값이 26보다 클때도 가능하도록 하기
n = n -26
x =[] # 암호화 하고 싶은 문장이 들어갈 공간
for i in range(0,len(m)):
x.append(m[i]) # x를 리스트화 하는 중
for i in range(0,len(m)):
for o in range(0,26):
if x[i] == c[o]: # x를 숫자로 바꾸어 주는 작업
r = int(o) + int(n) # r은 x를 숫자로 바꾼 값 (o) + 키값을 더해주어 암호화(현재 숫자)
while r>=26:
r = r-26 # 암호화한 값이 26보다 크면 리스트에 없기 때문에 거르는 작업
ab.append(c[int(r)]) # ab리스트(암호)에다가 암호화된 숫자값을 다시 문자로 변환하는 과정
for i in range(0,len(ab)):
print(ab[i],end='') # ab리스트 안의 문자들을 1열로 출력하는 과정
코딩 시작한지 3일된 초보입니다 개선할 부분이나 알고 있으면 좋을 법한 코드들 알려주시면 감사하겠습니다 ^^ (시작한지 얼마 되지 않아서 기본적인 코드들 밖에 없습니다.....ㅜㅜ)
def islower(chr1):
if ord(chr1) >= 97 and ord(chr1)<=122:
return 1
n=int(input())
str1=input()
list1=[]
for i in range(len(str1)):
if islower(str1[i]) == 1:
if ord(str1[i])+n > 97 and ord(str1[i])+n <= 122:
list1.append(chr( ord(str1[i])+n ))
else:
list1.append(chr( (ord(str1[i])+n)-122 + 97-1))
else:
if ord(str1[i])+n > 65 and ord(str1[i])+n <= 90:
list1.append(chr(ord(str1[i]) + n))
else:
list1.append(chr(ord(str1[i])+n-90+65-1))
for i in list1:
print(i,end="")
cha = input("대문자 알파벳을 입력하세요:")
n = int(input("암호화 변수 n을 입력하세요:"))
new_cha = ''
if n >= 26:
while n > 26:
n = n - 26
for i in cha:
if ord(i) + n > ord('Z'):
new_cha += chr(ord(i) + n - 26)
else:
new_cha += chr(ord(i) + n)
print(new_cha)
아스키 코드를 사용하는 프로그램을 작성하였습니다. n을 더했을 때 알파벳Z의 아스키코드를 넘어가버리면 다시 A로 되돌아오게끔 설정하였고, n이 아주 큰 수로 들어왔을 땐 26이하의 숫자로 변환하여 들어오게끔하였습니다. 그러다보니 소문자와 섞어서 쓸 수가 없어서 대문자로 국한시켜 표현하였습니다..
Python Code
Alph = [chr(i) for i in range(ord('A'), ord('Z')+1)]
Question = list('CAT')
n = 5
for x in Question:
print(Alph[Alph.index(x)+n], end="")
char = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def f():
word = input('Input Word in Capital : ')
n = int(input('Input Number : '))
result = ''
for i, v in enumerate(word):
result += char[(char.find(v)+n)]
return result
if __name__ == '__main__':
print(f())
word = input("word: ")
num = int(input("number: "))
alph = 'aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ'
output = ''
for x in word:
i_cur = alph.index(x)
i_num = i_cur + num*2
if i_num > 52-1:
i_num -= 52
else:
pass
output += alph[i_num]
print(output)
a='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
b=input("암호화 할 단어를 입력하세요 : ")
q = b.upper()
n=int(input("암호숫자를 지정하세요"))
c=[]
for j in range(len(q)):
for i in range(len(a)):
if q[j]==a[i]:
c.append(a[i+n])
print(''.join(c))
alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
input_str = 'CATTA'
result = []
n = 20
for i in range(len(input_str)):
for k in range(len(alpha)):
if input_str[i] == alpha[k]:
result.append(alpha[(k+n)%26])
print("".join(result))
sentence = input("문장을 입력하세요. :")
n = int(input("숫자를 입력하세요. :"))
code = ""
for i in range(len(sentence)):
if ord(sentence[i])+n <= 90:
code += chr(ord(sentence[i]) + n)
else:
code += chr(ord(sentence[i]) + n - 26)
print(code)
list로 계속 하다가 안 돼서 풀이 참고했는데 ord, chr이 있는줄 몰랐네요
alphabet=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q',
'R','S','T','U','V','W','X','Y','Z']
x=input('입력')
n=int(input('n개 뒤에'))
result=''
for i in x:
a=alphabet.index(i)
result+=alphabet[a+n]
print(result)
소문자도 작동하게 하고 싶으시다면 대문자 앞(혹은 뒤)에 각각 추가해 주시면 됩니다.
char_list = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
usr_str = input('문자열: ')
number = int(input('이동숫자: '))
crypt_str = ''
for i in usr_str:
tmp_num = char_list.find(i)+number
crypt_str += char_list[tmp_num%len(char_list)]
print(crypt_str)
>>> ord('A')
65
>>> ord('Z')
90
>>> def encrypt(text, n):
... f = ''.join([chr(i) for i in range(65, 91)])
... t = f[n:] + f[0:n]
... ttable = str.maketrans(f, t)
... return text.translate(ttable)
...
>>> encrypt('CAT', 5)
'HFY'
#collections 의 deque를 사용하였습니다.
import collections
def alpha_rotate(string1,shift_num):
abc = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
input_list = list(string1.upper())
abc_q = collections.deque(abc)
abc_q.rotate(-shift_num)
for i in input_list:
j = abc.index(i)
print(list(abc_q)[j],end=' ')
s = "CAT".lower()
n = 5
alphabet = 'abcdefghijklmnopqrstuvwxyz'
new = []
for i in s: #n은 문장이기 때문에 이미 문자의 형태임
a = alphabet[alphabet.find(i)+n]
new.append(a)
print(''.join(new))
Scanner sc = new Scanner(System.in);
System.out.println("숫자를 입력해주세요: "); // 숫자입력
int num = sc.nextInt();
System.out.println("문자를 입력해주세요: "); // 문자 입력
String words = sc.next();
System.out.println(words.length()); // 문자 배열틀 만들기
char[] word = new char[words.length()];
for(int i = 0; i < word.length; i++) { // 입력문자 배열에 집어넣기
word[i] = (char)(words.charAt(i)+num);
if( word[i] > 90 || word[i] < 65) {
word[i] = (char)('A'+((word[i]%90)%26)-1);
}
System.out.print(word[i]);
}
sc.close();
java
import java.util.Arrays;
import java.util.Scanner;
public class Caesar {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("단어를 입력하세요 : ");
String input = sc.next();
char[] cat = input.toCharArray();
System.out.println("밀어내고자 하는 횟수 : ");
int pass = sc.nextInt();
if(pass>26) {
pass = pass%26;
}
for (int i = 0; i < cat.length; i++) {
if(cat[i]>='a' && cat[i]<='z') {
if(cat[i] + pass >'z') {
cat[i] = (char) (cat[i] + pass - 26);
}else {
cat[i] = (char) (cat[i] + pass);
}
} else if(cat[i]>='A' && cat[i]<='Z') {
if(cat[i] + pass >'Z') {
cat[i] = (char) (cat[i] + pass - 26);
}else {
cat[i] = (char) (cat[i] + pass);
}
} else {
System.out.println("단어가 아닙니다.");
}
}
System.out.println(Arrays.toString(cat));
sc.close();
}
}
소문자는 소문자대로 변환 대문자는 대문자대로 변환
def caesar_cipher():
alp = "abcdefghijklmnopqrstuvwxyz"
sentence = input("문장을 입력하세요 : ")
n = int(input("n 지정 : "))
new_sentence = ""
for i in range(0, len(sentence)):
pivot = alp.find(sentence[i])
pivot += n
new_sentence += alp[pivot]
return new_sentence
print(caesar_cipher())
#codingdojing_caesar
#고려할 것
#대문자 소문자
#Z면, 다시 처음으로?
#A-Z: 65-90
#a-z: 97-122
#문장부호는 제외?
def caesarCode():
n = eval(input("enter the caesar Number: "))%26 #암호화 숫자가 큰 경우
sentence = input("enter the sentence: ")
newS = []
for c in sentence:
if ord(c) in range(65, 91): #upper
newS.append(chr(ord(c)+n)) if (ord(c)+n) < 91 else newS.append(chr(ord(c)+n-26))
elif ord(c) in range(97, 123): #lower
newS.append(chr(ord(c)+n)) if (ord(c)+n) < 123 else newS.append(chr(ord(c)+n-26))
else:
newS.append(c)
print(''.join(newS))
caesarCode()
파이썬으로 작성했습니다.
print(ord('a'), ord('z')) # 97~122 => 97~117
print(ord('A'), ord('Z')) # 65~90 => 65~85
code = input("영어로된 문자열 입력")
encoded = []
for c in code:
uni = ord(c)
if 97 <= uni and uni <= 117:
encoded.append(chr(uni + 5))
elif 117 < uni and uni <= 122:
temp = 122 - uni
encoded.append(chr(uni + 5 - 25 - 1))
elif 65 <= uni and uni <= 85:
encoded.append(chr(uni + 5))
elif 85 < uni and uni <= 90:
temp = 122 - uni
encoded.append(chr(uni + 5 - 25 - 1))
else:
encoded.append(c)
print(''.join(encoded))
sen, n = input('알파벳 대문자 문장과 숫자를 입력하세요: ').split()
list_sen = list(sen) n = int(n) list_password = []
for i in list_sen: password = ord(i) + n if password > 90: password = password - 26 list_password.append(chr(password))
print(''.join(list_password))
문자열을 사용하여 문제를 풀어보았습니다
sentense=input("암호를 만들 문장을 입력하세요:")
n=int(input("n을 입력하세요:"))
alphabat="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
result=""
for i in sentense:
sentense_index=alphabat.index(i)
index=sentense_index+n
result+=alphabat[index]
print(result)
abc = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R","S", "T", "U", "V", "W", "X", "Y", "Z"]
a = int(input("숫자입력: "))
b = str(input("문자입력: "))
b = list(b)
for i in range(len(b)):
for r in range(len(abc)):
d = []
if b[i] == abc[r]:
d = r+a
if 25 < d:
d = r+a-25
b[i] = abc[d]
break
print(b)
AlphabetList='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
code=input("code:")
n=int(input("n:"))
for str in code: print(AlphabetList[(AlphabetList.index(str)+n)%26])
s=input('단어 : ')
n=input('숫자 : ')
result=''
for i in s:
x=chr(ord(i)+int(n))
result+=x
print(result)
alpha = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','V','Z']
a = input('알파벳을 입력하시오 : ')
n = int(input('n을 입력하시오 : '))
SO =''
for i in a:
j = alpha.index(i)
b = alpha[j + n]
SO += b
print(SO)
static void caesarIsCode(String x) {
for (int i = 0; i < x.length(); i++) {
if ('A' <= x.charAt(i) && x.charAt(i) <= 'Z') { // 대문자
if ((x.charAt(i) + 5) > 90) {
System.out.print(Character.toString((x.charAt(i) + 5) - 90 + 64));
} else
System.out.print(Character.toString(x.charAt(i) + 5));
} else { // 소문자
if ((x.charAt(i) + 5) > 122) {
System.out.print(Character.toString((x.charAt(i) + 5) - 122 + 96));
} else
System.out.print(Character.toString(x.charAt(i) + 5));
}
}
System.out.println();
}
public static void main(String[] args) {
caesarIsCode("CAT");
caesarIsCode("JYP");
caesarIsCode("JyP");
}
a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
sentence = str(input("문장을 입력하시오"))
def solution (sent,n) :
m = list("".join(sent))
for k in range(len(sent)) :
m[k] = a[(a.index(m[k]))+n]
print("".join(m))
solution(sentence,5)
n = int(input('n을 입력해주세요.'))
alpha='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
word = input('암호를 만들 문장을 입력해주세요').upper()
print(''.join([alpha[j+5] for i in word for j in range(len(alpha)) if i == alpha[j]]))
package org.javaturotials.ex;
import java.util.*;
public class test {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
String code =sc.nextLine();
int num =sc.nextInt();
char[] arr = new char[code.length()];
for(int i=0; i<code.length(); i++) {
int c= Integer.valueOf(code.charAt(i));
c+=num;
arr[i]=(char)c;
}
for(int i=0; i<arr.length; i++) {
System.out.print(arr[i]);
}
}
}
package com.algorithm.algorithmpractice.dojang;
public class No {
public static void main(String[] args) {
String input = "asdjfklasdASDFZZKVOQRJGOJasdjfklaweqbozcxv";
char[] charArr = new char[input.length()];
int n = 5;
for (int i = 0; i < input.length(); i++) {
if ('a' <= input.charAt(i) && input.charAt(i) <= 'z') {
if(input.charAt(i)+n > 'z'){
char add = (char) ('a' + input.charAt(i) + n - 'z' -1);
charArr[i] = add;
}else {
char add = (char) (input.charAt(i) + n);
charArr[i] = add;
}
}
if ('A' <= input.charAt(i) && input.charAt(i) <= 'Z') {
if(input.charAt(i)+n > 'Z'){
char add = (char)('A'+input.charAt(i)+n-'Z'-1);
charArr[i] = add;
}else {
char add = (char) (input.charAt(i) + n);
charArr[i] = add;
}
}
}
System.out.println(new StringBuffer().append(charArr).toString());
}
}
다른 언어하다가 자바로 하려니까 힘드네요
#파이썬입니다. 띄워쓰기 안되요 ..ㅎ
from collections import deque
list = [x for x in 'abcdefghijklmnopqrstuvwxyz']
dequelist = deque(list)
secret_numbers = []
dequelist.rotate(-int(input("n을 지정해주세요. : ")))
S = input("암호화할 문장을 입력하세요. : ")
for i in S:
secret_numbers.append(list.index(i))
for i in secret_numbers:
print(dequelist[i],end='')
alphabet = 'abcdefghijklmnopqrstuvwxyz'
code1 = input("Enter word:")
a = 0
for i in code1: #code1 = 'letter'이면
n = alphabet.index(i) #i가 몇번째 알파벳인지 알았음
n = n+5 #5번 미룸
code2 = list(code1)
code2[a] = str(alphabet[n])
code1 = "".join(code2)
a += 1
print(code1)
text=''.join(filter(str.isalnum,input("문장을 입력하세요 : ").replace(" ","").lower()))
n= int(input('숫자를 입력하세요 : '))
for i in text:
if alphabet_list.index(i)+n > 25 :
print(alphabet_list[alphabet_list.index(i)+n-26], end="")
else :
print(alphabet_list[alphabet_list.index(i)+n], end="")
대문자는 소문자로 변환하고 특수문자는 제거하였습니다
def Caesar_Code(code, num):
asci_Code = [[chr(i) for i in range(ord('A'), ord('Z') + 1)], [chr(i) for i in range(ord('a'), ord('z') + 1)]]
for i in range(0, len(code)):
set_num = ord('A') if ord(code[i]) <= ord('Z') else ord('a')
cul_num = ord(code[i]) + int(num) - set_num
result = cul_num - len(asci_Code[0]) if cul_num >= len(asci_Code[0]) else cul_num
print(asci_Code[divmod(set_num, ord('a'))[0]][result], end='')
print('어떠한 암호를 만들 문장과 n을 입력했을 때 암호를 만들어 출력하는 프로그램입니다.')
code = input('암호로 만들 문장을 입력해주세요 : ')
num = input('숫자를 입력해주세요 : ')
Caesar_Code(code, num)
아스키코드를 최대한 사용하여 대문자, 소문자를 같이 써도 작동하게끔 만들었습니다.
python
sen = input("암호를 만들 문장: ")
n = int(input("n을 입력 하시오: "))
secret = ''
for i in range(len(sen)):
#입력 받은 문자가 알파벳이 아닐 때
if ord(sen[i]) < 65 or 90 < ord(sen[i]) < 97 or ord(sen[i]) > 122:
index = ord(sen[i])
#ascii에서 n개 뒤에 오는 문자가 알파벳이 아닐 때, A(a)로 돌아가 카운트
elif ord(sen[i]) <= 90 and ord(sen[i])+n > 90:
index = ord(sen[i])+n-90+64
elif ord(sen[i]) >= 97 and ord(sen[i])+n > 122:
index = ord(sen[i])+n-122+96
#그 외의 알파벳
else:
index = ord(sen[i])+n
secret += chr(index)
print(secret)
private static String cisor(String str, int n) {
ArrayList<Character> alphabet = new ArrayList<>();
String result = str; //입력값
String result1 = ""; //n번째 뒤 출력될 결과물
for(int i=0; i<26; i++) {
alphabet.add((char)(65+i));
}
alphabet.addAll(alphabet);
for(int i=0; i<str.length(); i++) {
char cha = result.charAt(i);
int idx = alphabet.indexOf(cha); //cha의 인덱스
result1 += alphabet.get(idx + n);
}
return result1;
}
파이썬입니다.
small_alphabet_list = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
#소문자 리스트
large_alphabet_list = []
for i in small_alphabet_list : #대문자 리스트
large_alphabet_list.append(i.upper())
def find_alphabet(a) : #리스트의 몇번째에 있는지 가져오기.
if a.isupper() :
for i in range(len(large_alphabet_list) - 1) :
if large_alphabet_list[i] == a :
return i
else :
for i in range(len(small_alphabet_list) - 1) :
if small_alphabet_list[i] == a :
return i
user_input = input("문자열 입력 : ")
nums = int(input("숫자 입력 : "))
result = ''
for i in user_input :
result_num = find_alphabet(i) + nums
if i.isupper() : # 대문자일때 처리
if result_num + nums > 25 : # 만약 값이 리스트 길이를 초과한다면
result_num -= 26
result = result + large_alphabet_list[result_num]
else :
result = result + large_alphabet_list[result_num]
else :
if result_num + nums > 25 : # 만약 값이 리스트 길이를 초과한다면
result_num -= 26
result = result + small_alphabet_list[result_num]
else :
result = result + small_alphabet_list[result_num]
print(result)
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
n = int(input())
phrase = input().upper()
newPhrase = ''
for i in range(len(phrase)):
if alphabet.find(phrase[i]) + n > 25:
newPhrase += alphabet[alphabet.find(phrase[i]) + n - 26]
else :
newPhrase += alphabet[alphabet.find(phrase[i]) + n]
print(newPhrase)
Python
al = "abcdefghijklmnopqrstuvwxyz"
sentence = input("암호화할 문장을 입력: ")
n = int(input("암호화에 쓸 변수를 입력: "))
result = []
for x in sentence: # 입력받은 문장의 각 글자를 요소로 순환
for c, y in enumerate(al): # 전체 알파벳 리스트를 순환, c는 그 인덱스
c2 = c+3 if c+3<27 else c+3-26 # 암호화 후 알파벳 인덱스
# 소문자일 경우
if x == y:
result.append(al[c2])
break
# 대문자일 경우
elif x.lower() == y:
result.append(al[c2].upper())
break
# 둘 다 아닐 경우
else:
result.append(x)
break
print(''.join(result))
파이썬으로 무식하게 풀었습니다. 대문자는 대문자끼리, 소문자는 소문자끼리 순환합니다. (ex : Z에 3이면 C, z에 3이면 c가 나옴) 공백문자나 문장부호는 그대로 남습니다.
import string
l_letter = [i for i in string.ascii_lowercase]
u_letter = [j for j in string.ascii_uppercase]
letters = l_letter + u_letter
num = int(input("Val:"))
data = list(input("Message:"))
code = []
for k in range(len(data)):
if data[i].isalpha():
c_index = letters.indes(data[i])
code.append(letters[(c_index + num) % 52])
else:
code.append(data[i])
print(('').join(code))
alpha='a b c d e f g h i j k l m n o p q r s t u v w x y z'.split()
def change(n):
words = input("너가 바꾸고싶은 영어단어를 입력해라")
answer=''
for i in words:
answer += alpha[alpha.index(i)+n]
return answer
print(change(3))
using System;
using System.Collections.Generic;
namespace solution
{
class Program
{
static void Main(string[] args)
{
Console.Write("암호를 만들 문장: ");
string sentence = Console.ReadLine();
Console.Write("n: ");
int N = int.Parse(Console.ReadLine());
Console.WriteLine("\n {0}", createPassword(sentence, N));
}
private static string createPassword(string sentence, int N)
{
List<char> letters = new List<char>();
for (int i = 0; i < 26; i++)
{
letters.Add((char)('a' + i));
letters.Add((char)('A' + i));
}
string caesarCode = "";
for (int i = 0; i < sentence.Length; i++)
{
if (letters.Contains(sentence[i]))
caesarCode += letters[(letters.IndexOf(sentence[i]) + 2 * N) % 52];
else
caesarCode += sentence[i];
}
return caesarCode;
}
}
}
int main() { int n; char str[100] = "CAT";
scanf("%d", &n);
for(int i=0; i<strlen(str); i++){
str[i] = str[i] + n;
}
printf("%s\n", str);
return 0;
}
def cipher(sentence,n):
alpha = list('abcdefghijklmnopqrstuvwxyz')
cipher = list(sentence.lower())
for i in range(len(cipher)) :
new_n = alpha.index(cipher[i]) + n
if new_n > 25 :
new_n -= 26
cipher[i] = alpha[new_n]
return ("".join(cipher)).upper()
def cipher(sentence,n):
alpha = list('abcdefghijklmnopqrstuvwxyz')
cipher = list(sentence.lower())
for i in range(len(cipher)) :
if cipher[i] != " " :
new_n = alpha.index(cipher[i]) + n
if new_n > 25 :
new_n -= 26
cipher[i] = alpha[new_n]
else :
cipher[i] = cipher[i]
return ("".join(cipher)).upper()
alph = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
alphabet = list(alph)
n = int(input("비밀 로직 수 입력: ")) % 26
word = input("문자 입력: ").upper()
chword = []
for ch in word:
if ch in alphabet:
chword.append(alphabet[(alphabet.index(ch) + n) % 26])
else:
chword.append(ch)
print("".join(chword))
text = input('Enter texts: ')
number = int(input('Enter number: '))
result = []
for c in text:
if 'A' <= c <= 'Z':
result.append(chr((ord(c) - ord('A') + number) % 26 + ord('A')))
elif 'a' <= c <= 'z':
result.append(chr((ord(c) - ord('a') + number) % 26 + ord('a')))
else:
result.append(c)
print(''.join(result))