blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
cc19babd5a8b1698c5b1aca0dfdb29122ee2e494
seungmin001/programmers
/hash/전화번호목록.py
233
3.796875
4
def solution(phone_book): answer = True dict={} phone_book.sort() before='a' # 첫번째 for p in phone_book: if before in p: return False before=p return answer
2d30aaf0eddd3a054f84063e3d6971b4933097af
irosario1999/30days-of-python
/day_2/variables.py
1,014
4.125
4
from math import pi print("Day 2: 30 days of python") firstName = "ivan" lastName = "Rosario" fullName = firstName + " " + lastName country = "US" city = "miami" age = "21" year = "2020" is_married = False is_true = True is_light_on = False i, j = 0, 3 print(type(firstName)) print(type(lastName)) print(type(fullName)) print(type(country)) print(type(city)) print(type(age)) print(type(year)) print(type(is_married)) print(type(is_true)) print(type(is_light_on)) print(type(i)) print(type(j)) print("firstName length:", len(firstName)) print("diff of firstname and lastname", len(firstName) - len(lastName)) num_one, num_two = 5, 4 _total = num_one + num_two _diff = num_two - num_one _product = num_two * num_one _division = num_one / num_two _floor_division = num_two % num_one radius = input("insert radius: ") area_of_circle = pi * radius ** 2 circum_of_circle = 2 * pi * radius print(circum_of_circle) print(area_of_circle) # name = input("firstname: ") # last = input("lastName: ") help("keywords")
f884b87a05f26d501e7c03a1076580bf5d3db646
eweisger/Diffie-Hellman-HTTP-Host-and-Client
/diffieHellmanHTTPServers/task2.py
3,817
3.515625
4
#Emma Weisgerber #CSCI 373: Intro to Cyber Security - Dr. Brian Drawert #Homework 2: Cryptography - 2/18/19 #----------------------------------------------------- #Program which implements the Affine substitution cypher #Uses the character set of ASCII code 32 through 126 for a total of 95 characters, and ignores the new line character #Using a multiplyer of 13 and an offset of 7 it reads in the task2 encrypted message and writes out the decrypted message #Stack overflow and man pages were referenced #----------------------------------------------------- #Modified for Networking Lab2 - 4/16/19 import string multiplier_list = [1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 21, 22, 23, 24, 26, 27, 28, 29, 31, 32, 33, 34, 36, 37, 39] def affine_cipher(): multiplier = 13 offset = 7 with open("task2_encrypted_message.txt", "r") as input_message: encrypted_message = input_message.read() decrypted_message = decrypt(encrypted_message, multiplier, offset) with open("task2_decrypted_message.txt", "w") as output_message: output_message.write(decrypted_message) #Used to test encryption #with open("test_encryption.txt", "w") as test: #test.write(encrypt(decrypted_message, multiplier, offset)) def decrypt(cyphertext, multiplier_index, offset): key = decryption_key(multiplier_index, offset) character_set = [chr(i) for i in range(32, 127)] print("character set length {0}".format(len(character_set))) #For each character in the cyphertext, check to make sure it's a valid character for i in range(len(cyphertext)): if cyphertext[i] not in '\n\r'+"".join(character_set): print("Invalid character: '{0}'".format(cyphertext[i])) return #For each character in the cyphertext, decrypt the character using the key and replace it with the unencrypted character, ignoring the new line character plaintext = '' for i in range(len(cyphertext)): if (cyphertext[i] == '\n') or (cyphertext[i] == '\r'): plaintext += cyphertext[i] else: plaintext += key[cyphertext[i]] return plaintext def decryption_key(multiplier_index, offset): character_set = [chr(i) for i in range(32, 127)] #Create key for each encrypted character with its corresponding unencrypted character within the character set key = {} for i in range(len(character_set)): j = ((multiplier_list[multiplier_index]*i + offset))%(len(character_set)) key[character_set[j]] = character_set[i] return key def encrypt(plaintext, multiplier_index, offset): key = encryption_key(multiplier_index, offset) character_set = [chr(i) for i in range(32, 127)] #For each character in the plaintext, check to make sure it's a valid character for i in range(len(plaintext)): if plaintext[i] not in '\n\r'+"".join(character_set): print("Invalid character: '{0}'".format(plaintext[i])) return #For each character in the plaintext, encrypt the character using the key and replace it with the encrypted character, ignoring the new line character cyphertext = '' for i in range(len(plaintext)): if (plaintext[i] == '\n') or (plaintext[i] == '\r'): cyphertext += plaintext[i] else: cyphertext += key[plaintext[i]] return cyphertext def encryption_key(multiplier_index, offset): character_set = [chr(i) for i in range(32, 127)] #Create key for each character with its corresponding encrypted character within the set key = {} for i in range(len(character_set)): j = ((multiplier_list[multiplier_index]*i + offset))%(len(character_set)) key[character_set[i]] = character_set[j] return key if __name__ == "__main__": affine_cipher()
34aa56f0a0d252b2aef9d420be28d23106725a3d
vlapparov/Ecole42
/Django/d01/ex00/var.py
550
3.734375
4
# coding: utf-8 # In[9]: # 42 est de type <class 'int'> # 42 est de type <class 'str'> # quarante-deux est de type <class 'str'> # 42.0 est de type <class 'float'> # True est de type <class 'bool'> # [42] est de type <class 'list'> # {42: 42} est de type <class 'dict'> # (42,) est de type <class 'tuple'> # set() est de type <class 'set'> l = [42, '42', 'quarante-deux', 42.0, True, [42], {42:42}, (42,), set()] def my_var(): for i in l: print(str(i) + ' est de type ' + str(type(i))) if __name__ == '__main__': my_var()
a6e227d28ed371a8516d468b9b870323a6144695
vs359268/pythonUtils
/01.pdf_split.py
943
3.578125
4
# -*- coding:utf-8 -*- # @Time : 2021/3/8 18:46 # @Author: Sun Hao # @Description: 根据页数切割pdf文件 # @File : 01.pdf_split.py from PyPDF2 import PdfFileReader, PdfFileWriter def split_single_pdf(read_file, start_page, end_page, pdf_file): #1.获取原始pdf文件 fp_read_file = open(read_file, 'rb') #2.将要分割的pdf内容格式化 pdf_input = PdfFileReader(fp_read_file) #3.实例一个pdf文件编写器 pdf_output = PdfFileWriter() for i in range(start_page, end_page): pdf_output.addPage(pdf_input.getPage(i)) #4.写pdf文件 with open(pdf_file, 'wb') as pdf_out: pdf_output.write(pdf_out) print(f'{read_file}分割{start_page}页-{end_page}页完成,保存为{pdf_file}!') if __name__ == '__main__': input_pdf_name = "input.pdf" output_pdf_name = 'output.pdf' start = 1 end = 2 split_single_pdf(input_pdf_name, start, end, output_pdf_name)
d0217754668282cca99a70d421775c2fa574c1c9
atreanor/FlightCalculator
/Aircraft.py
545
3.734375
4
class Aircraft: """ a class to store Airport objects """ def __init__(self, code, units, range): """ class constructor initialises variables with input """ self.code = code self.units = units self.range = range def get_range(self): """ method to retrieve aircraft range """ return self.range def __str__(self): """ string method to return a descriptive output """ return str("Aircraft Code: " + self.code + " Units: " + self.units + " range: " + self.range)
d64d1b8b956ba1bb55895093fe0b1bea1c240bea
lhwylpdpn/IIT_study
/cs430/cs430-greedy.py
1,573
3.703125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import time class Q9(): def __init__(self,cell): self.cell=cell for r in self.cell: r.insert(0,1)#每行首加阻碍 r.append(1)#每行尾巴加阻碍 self.cell.insert(0,[1]*len(cell[0])) self.cell.append([1]*len(cell[0])) print(cell) self.value = [[-1]*(len(cell[0])) for i in range(len(cell))] def recursively_withoutmem(self,i,j):# 得到到达这个点的可能之和 if self.cell[i][j]==0: if i==1 and j==1: return 1 if self.value[i][j]>0: # print('alreay',i,j) return self.value[i][j] if self.cell[i-1][j]==1 and self.cell[i][j-1]==1: #up 1 left 1 over # print('a',i,j) self.value[i][j]=0 return 0 elif self.cell[i-1][j]==0 and self.cell[i][j-1]==0:#up 0 left 0 两种过来的可能之和 # print('b',i,j) self.value[i][j]=self.recursively_withoutmem(i-1,j)+ self.recursively_withoutmem(i,j-1) return self.value[i][j] elif self.cell[i-1][j]==1 and self.cell[i][j-1]==0: #up1 left 0 self.value[i][j]=self.recursively_withoutmem(i,j-1) return self.value[i][j] else: self.value[i][j]=self.recursively_withoutmem(i-1,j) return self.value[i][j] else: return 0
ff3984153b82e47887a4621b85c660b5cd262916
n20084753/Guvi-Problems
/beginer/set-2/print-even-values-in-range.py
175
3.625
4
import sys m, n = [int(x) for x in raw_input().split(" ")] evenValues = [] for i in range(m+1, n): if (i & 1) == 0: evenValues.append(str(i)) print(' '.join(evenValues))
c0d3eda8788a772005f3c4d51d21c3454c6d2162
n20084753/Guvi-Problems
/beginer/set-6/60-fibonacci-series.py
241
3.6875
4
def fibo(n): if n < 2: return 1 if memo[n] != 0: return memo[n] memo[n] = fibo(n-2) + fibo(n-1) return memo[n] n = int(raw_input()) memo = [0 for i in range(n)] memo[0] = memo[1] = 1 fibo(n-1) print(" ".join(str(x) for x in memo))
ed8fb302f599d4f5f37e4cfa061fc60d1763cab3
n20084753/Guvi-Problems
/beginer/set-11/109-minimum-in-array.py
131
3.890625
4
values = [int(x) for x in raw_input().split(" ")] min = float('inf') for item in values: if item < min: min = item print(min)
274ff48adcbd3e8986f0e38ce819581137a82446
n20084753/Guvi-Problems
/beginer/set-5/43-strcat.py
159
3.609375
4
def myStrcat(s1, s2): s3 = '' for s in s1: s3 += s for s in s2: s3 += s return s3 s1, s2 = [x for x in raw_input().split()] print(myStrcat(s1, s2))
edf44d91616f17cec7f142b595b81661c6115386
n20084753/Guvi-Problems
/is-alphabet.py
108
3.5
4
import sys input = sys.stdin.readline().rstrip() if input.isalpha(): print("Alphabet") else: print("No")
db5b84c9356adf31355f0eb0656752405a4ea3fa
n20084753/Guvi-Problems
/beginer/set-7/64-is-sum-odd-or-even.py
134
3.78125
4
n, m = [int(x) for x in raw_input().split(" ")] print("even" if (n & 1 == 0 and m & 1 == 0) or (n & 1 != 0 and m & 1 != 0) else "odd")
4bfb363c4d4daa59ab642e6280384a5fa38c0185
n20084753/Guvi-Problems
/beginer/set-3/is-numeric.py
295
3.859375
4
def isNumber(str): if str[0] != '-' and not str[0].isdigit(): return False if str[0] == '-' and len(str) == 1: return False for i in range(1, len(str)): if not str[i].isdigit(): return False return True input = raw_input() if (isNumber(input)): print("Yes") else: print("No")
3d84235eed2e481dde2e5a4e0822e9ed72a8016e
n20084753/Guvi-Problems
/beginer/set-8/80-print-odd-digits-in-number.py
162
3.6875
4
n = int(raw_input()) digits = [] while n > 0: r = n % 10 if r & 1 != 0: digits.append(str(r)) n = n / 10 digits = reversed(digits) print(" ".join(digits))
a78a83d12fcfe61a67491e5a23ff2a6ebadb1b56
wercabaj/BankingSystem
/main.py
7,409
3.828125
4
import random import sqlite3 conn = sqlite3.connect('card.s3db') cur = conn.cursor() cur.execute('CREATE TABLE IF NOT EXISTS card (id INTEGER, number TEXT, pin TEXT, balance INTEGER DEFAULT 0);') conn.commit() def menu(): print("""1. Create an account 2. Log into account 0. Exit""") def dont_exist(user_enter): total = 0 tab = user_enter.split() for i in range(len(tab)): if i % 2 == 0: new_value = int(tab[i]) * 2 if new_value > 9: new_value = new_value - 9 tab[i] = str(new_value) total += int(tab[i]) if total % 10 == 0: return False else: return True def logged_menu(data, choice): choice = -1 while choice != 0: print("1. Balance") print("2. Add income") print("3. Do transfer") print("4. Close account") print("5. Log out") print("0. Exit") choice = int(input()) if choice == 1: print() cur.execute("SELECT balance FROM card WHERE number = (?);", (data[0])) balance = cur.fetchall() print("Balance:", balance) print() elif choice == 2: print("Enter income:") income = int(input()) cur.execute("SELECT balance FROM card WHERE number = (?);", [data[0]]) balance = cur.fetchall() cur.execute("UPDATE card SET balance = (?) WHERE number = (?);", (income + balance[0][0], data[0])) conn.commit() print("Income was added!") elif choice == 3: print("Transfer") print("Enter card number:") user_enter = input() check = False cur.execute("SELECT number FROM card") sql_data = cur.fetchall() for d in sql_data: if d[0] == user_enter: check = True break if check: if data[0] == user_enter: print("You can't transfer money to the same account!") else: print("Enter how much money you want to transfer:") transfer = int(input()) cur.execute("SELECT balance FROM card WHERE number = (?);", [data[0]]) s_balance = cur.fetchall()[0][0] if transfer > s_balance: print("Not enough money!") else: s_balance -= transfer cur.execute("UPDATE card SET balance = (?) WHERE number = (?);", (s_balance, data[0])) conn.commit() cur.execute("SELECT balance FROM card WHERE number = (?);", [user_enter]) r_balance = cur.fetchall()[0][0] r_balance += transfer cur.execute("UPDATE card SET balance = (?) WHERE number = (?);", (r_balance, user_enter)) conn.commit() print("Success!") elif user_enter[0] != '4': print("Such a card does not exist.") elif dont_exist(user_enter): print("Probably you made a mistake in the card number. Please try again!") else: print("Such a card does not exist.") elif choice == 4: print("The account has been closed!") cur.execute("DELETE FROM card WHERE number = (?);", [data[0]]) conn.commit() elif choice == 5: print() print("You have successfully logged out!") print() choice = -1 return choice else: choice = 0 return choice def luhn_algoritm(card_number): new_card_number = list(card_number) new_value = 0 total = 0 x = 0 for i in range(15): if i % 2 == 0: new_value = int(new_card_number[i]) * 2 if new_value > 9: new_value = new_value - 9 new_card_number[i] = str(new_value) total += int(new_card_number[i]) for i in range(10): if (total + i) % 10 == 0: x = i break card_number = card_number + str(x) return card_number def generate_card_number(): random.seed() card_number = "400000" for i in range(9): r = random.randint(0, 9) card_number += str(r) card_number = luhn_algoritm(card_number) cur.execute("SELECT number FROM card") sql_data = cur.fetchall() if card_number not in sql_data: return card_number else: generate_card_number() def create_account(): random.seed() card_number = generate_card_number() PIN = "" for i in range(4): r = random.randint(0, 9) PIN += str(r) print() print("Your card has been created") print("Your card number:") print(card_number) print("Your card PIN:") print(PIN) print() return card_number, PIN logged = False choice = -1 card_id = 1 while choice != 0: menu() choice = int(input()) if choice == 1: card_number, PIN = create_account() cur.execute("INSERT INTO card VALUES (?, ?, ?, ?)", (card_id, card_number, PIN, 0)) conn.commit() card_id += 1 elif choice == 2: print() print("Enter your card number:") card_number = input() print("Enter your PIN:") PIN = input() cur.execute("SELECT number, pin, balance FROM card") data = cur.fetchall() conn.commit() for i in range(len(data)): if card_number == data[i][0]: if PIN == data[i][1]: logged = True print() print("You have successfully logged in!") print() new_data = [] new_data.append(data[i][0]) new_data.append(data[i][1]) new_data.append(data[i][2]) if logged == True: choice = logged_menu(new_data, choice) else: print() print("Wrong card number or PIN!") print() logged = False print() print("Bye!") conn.close()
d639304757ad0c96c4c57ad799392ab1e8e104f0
quangloan17/hocThayTung
/1.T6/15-06-lambda/tham_khao/h2.py
270
3.640625
4
x = input('nhập vào xâu dạng nhị phân = ') def changeofNumber(x): change = 0 p = len(x)-1 for i in range(len(x)): change += int(x[i]) * pow(2,p) p -= 1 return change print('chuyển đổi được',changeofNumber(x))
db87f57e50c33387e92206404aed0542ea459170
quangloan17/hocThayTung
/1.T6/05-06-vong-lap2/1_vi_du_ho_ten.py
357
3.703125
4
#todo: #Nhập vào: họ, tên đệm, tên #in ra: Họ và tên đầy đủ: ho = input('Họ bạn là gì: ') ten_dem = input('Tên đệm của bạn là gì: ') ten = input('Tên của bạn là gì: ') print(f'Tên của bạn đầy đủ là: {ho} {ten_dem} {ten}') print(f'Tên của bạn đầy đủ là: {ho}, {ten_dem}, {ten}')
a1c3bf809dfdf8569dc46b061b93842761fef1ad
quangloan17/hocThayTung
/1.T6/05-06-vong-lap2/bai_tham_khao/Trần Thành Công/BVN1buoi4.py
155
3.859375
4
str1=input("Input string: ") count=0 for i in range(len(str1)): if str1[i]!=" ": count+=1 print("Số ký tự có trong string:",count)
51d94b3471a96b5bcb2afde6bf7f3d9b90458cf4
quangloan17/hocThayTung
/1.T6/05-06-vong-lap2/1_thap_hanoi.py
323
3.828125
4
def hanoi(N , src, dst, temp): if N == 1: print('Chuyển đĩa 1 từ cọc', src, 'sang cọc ', dst) return hanoi(N-1, src, temp, dst) print('Chuyển đĩa' , N , 'từ cọc', src, 'sang cọc ', dst) hanoi(N-1, temp, dst, src) N = 4 hanoi(N, 1, 3, 2)
33bc583e75f8bf0ca967a5ce0e40b30c71450175
quangloan17/hocThayTung
/1.T6/01-06-vong-lap/bang_cuu_chuong2.py
98
3.546875
4
for j in range(2,11): print('') for i in range(2,11): print(f'{j}*{i}={j*i}')
c32ee8069bcc8369b6a760620d15a221c480638c
vipinkvpk/Data-Visualization-with-Python-project
/task1.py
246
3.609375
4
import pandas as pd import matplotlib.pyplot as plt df = pd.read_json (r'./rain.json') print(df) print("df statistics: " ,df.describe()) df.plot(x='Month', y ='Temperature') df.plot(x='Month', y = 'Rainfall') plt.show()
d84294ca3dea0a25671fcc4a5f97b9b958f5ee1e
MashodRana/NLP
/Speech_to_TextBangla_and_POS_tagger/posTagger.py
17,468
3.609375
4
# -*- coding: utf-8 -*- """ Created on Wed Feb 7 19:44:09 2018 @author: Sagar Hossain """ """ it takes a word then gives which parts of speech it is as a tuple as (word,nameOfpos) """ from xml.dom import minidom nouns=[] prons=[] verbs=[] adj=[] adv=[] conj=[] def gettinNouns(): xmldoc = minidom.parse('Noun.xml') itemlist = xmldoc.getElementsByTagName('noun') for s in itemlist: nouns.append(s.childNodes[0].nodeValue) def gettinProns(): xmldoc = minidom.parse('Pronoun.xml') itemlist = xmldoc.getElementsByTagName('pron') for s in itemlist: nouns.append(s.childNodes[0].nodeValue) def gettinVerbs(): xmldoc = minidom.parse('Verb.xml') itemlist = xmldoc.getElementsByTagName('verb') for s in itemlist: nouns.append(s.childNodes[0].nodeValue) def gettinPosLen2(): xmldoc = minidom.parse('L1_2.xml') itemlist1 = xmldoc.getElementsByTagName('noun') itemlist2 = xmldoc.getElementsByTagName('pron') itemlist3 = xmldoc.getElementsByTagName('adj') itemlist4 = xmldoc.getElementsByTagName('adv') itemlist5 = xmldoc.getElementsByTagName('verb') itemlist6 = xmldoc.getElementsByTagName('conj') for s in itemlist1: nouns.append(s.childNodes[0].nodeValue) for s in itemlist2: prons.append(s.childNodes[0].nodeValue) for s in itemlist3: adj.append(s.childNodes[0].nodeValue) for s in itemlist4: adv.append(s.childNodes[0].nodeValue) for s in itemlist5: verbs.append(s.childNodes[0].nodeValue) for s in itemlist6: conj.append(s.childNodes[0].nodeValue) def gettinPosLen3(): xmldoc = minidom.parse('L3.xml') itemlist1 = xmldoc.getElementsByTagName('noun') itemlist2 = xmldoc.getElementsByTagName('pron') itemlist3 = xmldoc.getElementsByTagName('adj') itemlist4 = xmldoc.getElementsByTagName('adv') itemlist5 = xmldoc.getElementsByTagName('verb') itemlist6 = xmldoc.getElementsByTagName('conj') for s in itemlist1: nouns.append(s.childNodes[0].nodeValue) for s in itemlist2: prons.append(s.childNodes[0].nodeValue) for s in itemlist3: adj.append(s.childNodes[0].nodeValue) for s in itemlist4: adv.append(s.childNodes[0].nodeValue) for s in itemlist5: verbs.append(s.childNodes[0].nodeValue) for s in itemlist6: conj.append(s.childNodes[0].nodeValue) def gettinPosLen4(): xmldoc = minidom.parse('L4.xml') itemlist1 = xmldoc.getElementsByTagName('noun') itemlist2 = xmldoc.getElementsByTagName('pron') itemlist3 = xmldoc.getElementsByTagName('adj') itemlist4 = xmldoc.getElementsByTagName('adv') itemlist5 = xmldoc.getElementsByTagName('verb') itemlist6 = xmldoc.getElementsByTagName('conj') for s in itemlist1: nouns.append(s.childNodes[0].nodeValue) for s in itemlist2: prons.append(s.childNodes[0].nodeValue) for s in itemlist3: adj.append(s.childNodes[0].nodeValue) for s in itemlist4: adv.append(s.childNodes[0].nodeValue) for s in itemlist5: verbs.append(s.childNodes[0].nodeValue) for s in itemlist6: conj.append(s.childNodes[0].nodeValue) def gettinPosLen5(): xmldoc = minidom.parse('L5.xml') itemlist1 = xmldoc.getElementsByTagName('noun') itemlist2 = xmldoc.getElementsByTagName('pron') itemlist3 = xmldoc.getElementsByTagName('adj') itemlist4 = xmldoc.getElementsByTagName('adv') itemlist5 = xmldoc.getElementsByTagName('verb') itemlist6 = xmldoc.getElementsByTagName('conj') for s in itemlist1: nouns.append(s.childNodes[0].nodeValue) for s in itemlist2: prons.append(s.childNodes[0].nodeValue) for s in itemlist3: adj.append(s.childNodes[0].nodeValue) for s in itemlist4: adv.append(s.childNodes[0].nodeValue) for s in itemlist5: verbs.append(s.childNodes[0].nodeValue) for s in itemlist6: conj.append(s.childNodes[0].nodeValue) def gettinPosLen6(): xmldoc = minidom.parse('L6.xml') itemlist1 = xmldoc.getElementsByTagName('noun') itemlist2 = xmldoc.getElementsByTagName('pron') itemlist3 = xmldoc.getElementsByTagName('adj') itemlist4 = xmldoc.getElementsByTagName('adv') itemlist5 = xmldoc.getElementsByTagName('verb') itemlist6 = xmldoc.getElementsByTagName('conj') for s in itemlist1: nouns.append(s.childNodes[0].nodeValue) for s in itemlist2: prons.append(s.childNodes[0].nodeValue) for s in itemlist3: adj.append(s.childNodes[0].nodeValue) for s in itemlist4: adv.append(s.childNodes[0].nodeValue) for s in itemlist5: verbs.append(s.childNodes[0].nodeValue) for s in itemlist6: conj.append(s.childNodes[0].nodeValue) def gettinPosLen7(): xmldoc = minidom.parse('L7.xml') itemlist1 = xmldoc.getElementsByTagName('noun') itemlist2 = xmldoc.getElementsByTagName('pron') itemlist3 = xmldoc.getElementsByTagName('adj') itemlist4 = xmldoc.getElementsByTagName('adv') itemlist5 = xmldoc.getElementsByTagName('verb') itemlist6 = xmldoc.getElementsByTagName('conj') for s in itemlist1: nouns.append(s.childNodes[0].nodeValue) for s in itemlist2: prons.append(s.childNodes[0].nodeValue) for s in itemlist3: adj.append(s.childNodes[0].nodeValue) for s in itemlist4: adv.append(s.childNodes[0].nodeValue) for s in itemlist5: verbs.append(s.childNodes[0].nodeValue) for s in itemlist6: conj.append(s.childNodes[0].nodeValue) def gettinPosLen8(): xmldoc = minidom.parse('L8.xml') itemlist1 = xmldoc.getElementsByTagName('noun') itemlist2 = xmldoc.getElementsByTagName('pron') itemlist3 = xmldoc.getElementsByTagName('adj') itemlist4 = xmldoc.getElementsByTagName('adv') itemlist5 = xmldoc.getElementsByTagName('verb') itemlist6 = xmldoc.getElementsByTagName('conj') for s in itemlist1: nouns.append(s.childNodes[0].nodeValue) for s in itemlist2: prons.append(s.childNodes[0].nodeValue) for s in itemlist3: adj.append(s.childNodes[0].nodeValue) for s in itemlist4: adv.append(s.childNodes[0].nodeValue) for s in itemlist5: verbs.append(s.childNodes[0].nodeValue) for s in itemlist6: conj.append(s.childNodes[0].nodeValue) def gettinPosLen9(): xmldoc = minidom.parse('L9.xml') itemlist1 = xmldoc.getElementsByTagName('noun') itemlist2 = xmldoc.getElementsByTagName('pron') itemlist3 = xmldoc.getElementsByTagName('adj') itemlist4 = xmldoc.getElementsByTagName('adv') itemlist5 = xmldoc.getElementsByTagName('verb') itemlist6 = xmldoc.getElementsByTagName('conj') for s in itemlist1: nouns.append(s.childNodes[0].nodeValue) for s in itemlist2: prons.append(s.childNodes[0].nodeValue) for s in itemlist3: adj.append(s.childNodes[0].nodeValue) for s in itemlist4: adv.append(s.childNodes[0].nodeValue) for s in itemlist5: verbs.append(s.childNodes[0].nodeValue) for s in itemlist6: conj.append(s.childNodes[0].nodeValue) def gettinPosLen10(): xmldoc = minidom.parse('L10.xml') itemlist1 = xmldoc.getElementsByTagName('noun') itemlist2 = xmldoc.getElementsByTagName('pron') itemlist3 = xmldoc.getElementsByTagName('adj') itemlist4 = xmldoc.getElementsByTagName('adv') itemlist5 = xmldoc.getElementsByTagName('verb') itemlist6 = xmldoc.getElementsByTagName('conj') for s in itemlist1: nouns.append(s.childNodes[0].nodeValue) for s in itemlist2: prons.append(s.childNodes[0].nodeValue) for s in itemlist3: adj.append(s.childNodes[0].nodeValue) for s in itemlist4: adv.append(s.childNodes[0].nodeValue) for s in itemlist5: verbs.append(s.childNodes[0].nodeValue) for s in itemlist6: conj.append(s.childNodes[0].nodeValue) def gettinPosLen11(): xmldoc = minidom.parse('L11.xml') itemlist1 = xmldoc.getElementsByTagName('noun') itemlist2 = xmldoc.getElementsByTagName('pron') itemlist3 = xmldoc.getElementsByTagName('adj') itemlist4 = xmldoc.getElementsByTagName('adv') itemlist5 = xmldoc.getElementsByTagName('verb') itemlist6 = xmldoc.getElementsByTagName('conj') for s in itemlist1: nouns.append(s.childNodes[0].nodeValue) for s in itemlist2: prons.append(s.childNodes[0].nodeValue) for s in itemlist3: adj.append(s.childNodes[0].nodeValue) for s in itemlist4: adv.append(s.childNodes[0].nodeValue) for s in itemlist5: verbs.append(s.childNodes[0].nodeValue) for s in itemlist6: conj.append(s.childNodes[0].nodeValue) def gettinPosLen12(): xmldoc = minidom.parse('L12.xml') itemlist1 = xmldoc.getElementsByTagName('noun') itemlist2 = xmldoc.getElementsByTagName('pron') itemlist3 = xmldoc.getElementsByTagName('adj') itemlist4 = xmldoc.getElementsByTagName('adv') itemlist5 = xmldoc.getElementsByTagName('verb') itemlist6 = xmldoc.getElementsByTagName('conj') for s in itemlist1: nouns.append(s.childNodes[0].nodeValue) for s in itemlist2: prons.append(s.childNodes[0].nodeValue) for s in itemlist3: adj.append(s.childNodes[0].nodeValue) for s in itemlist4: adv.append(s.childNodes[0].nodeValue) for s in itemlist5: verbs.append(s.childNodes[0].nodeValue) for s in itemlist6: conj.append(s.childNodes[0].nodeValue) def gettinPosLen13(): xmldoc = minidom.parse('L13.xml') itemlist1 = xmldoc.getElementsByTagName('noun') itemlist2 = xmldoc.getElementsByTagName('pron') itemlist3 = xmldoc.getElementsByTagName('adj') itemlist4 = xmldoc.getElementsByTagName('adv') itemlist5 = xmldoc.getElementsByTagName('verb') itemlist6 = xmldoc.getElementsByTagName('conj') for s in itemlist1: nouns.append(s.childNodes[0].nodeValue) for s in itemlist2: prons.append(s.childNodes[0].nodeValue) for s in itemlist3: adj.append(s.childNodes[0].nodeValue) for s in itemlist4: adv.append(s.childNodes[0].nodeValue) for s in itemlist5: verbs.append(s.childNodes[0].nodeValue) for s in itemlist6: conj.append(s.childNodes[0].nodeValue) def gettinPosLen14(): xmldoc = minidom.parse('L14.xml') itemlist1 = xmldoc.getElementsByTagName('noun') itemlist2 = xmldoc.getElementsByTagName('pron') itemlist3 = xmldoc.getElementsByTagName('adj') itemlist4 = xmldoc.getElementsByTagName('adv') itemlist5 = xmldoc.getElementsByTagName('verb') itemlist6 = xmldoc.getElementsByTagName('conj') for s in itemlist1: nouns.append(s.childNodes[0].nodeValue) for s in itemlist2: prons.append(s.childNodes[0].nodeValue) for s in itemlist3: adj.append(s.childNodes[0].nodeValue) for s in itemlist4: adv.append(s.childNodes[0].nodeValue) for s in itemlist5: verbs.append(s.childNodes[0].nodeValue) for s in itemlist6: conj.append(s.childNodes[0].nodeValue) def gettinPosLen15(): xmldoc = minidom.parse('L15.xml') itemlist1 = xmldoc.getElementsByTagName('noun') itemlist2 = xmldoc.getElementsByTagName('pron') itemlist3 = xmldoc.getElementsByTagName('adj') itemlist4 = xmldoc.getElementsByTagName('adv') itemlist5 = xmldoc.getElementsByTagName('verb') itemlist6 = xmldoc.getElementsByTagName('conj') for s in itemlist1: nouns.append(s.childNodes[0].nodeValue) for s in itemlist2: prons.append(s.childNodes[0].nodeValue) for s in itemlist3: adj.append(s.childNodes[0].nodeValue) for s in itemlist4: adv.append(s.childNodes[0].nodeValue) for s in itemlist5: verbs.append(s.childNodes[0].nodeValue) for s in itemlist6: conj.append(s.childNodes[0].nodeValue) def gettinPosLen16(): xmldoc = minidom.parse('L16.xml') itemlist1 = xmldoc.getElementsByTagName('noun') itemlist2 = xmldoc.getElementsByTagName('pron') itemlist3 = xmldoc.getElementsByTagName('adj') itemlist4 = xmldoc.getElementsByTagName('adv') itemlist5 = xmldoc.getElementsByTagName('verb') itemlist6 = xmldoc.getElementsByTagName('conj') for s in itemlist1: nouns.append(s.childNodes[0].nodeValue) for s in itemlist2: prons.append(s.childNodes[0].nodeValue) for s in itemlist3: adj.append(s.childNodes[0].nodeValue) for s in itemlist4: adv.append(s.childNodes[0].nodeValue) for s in itemlist5: verbs.append(s.childNodes[0].nodeValue) for s in itemlist6: conj.append(s.childNodes[0].nodeValue) def gettinPosLen17(): xmldoc = minidom.parse('L17.xml') itemlist1 = xmldoc.getElementsByTagName('noun') itemlist2 = xmldoc.getElementsByTagName('pron') itemlist3 = xmldoc.getElementsByTagName('adj') itemlist4 = xmldoc.getElementsByTagName('adv') itemlist5 = xmldoc.getElementsByTagName('verb') itemlist6 = xmldoc.getElementsByTagName('conj') for s in itemlist1: nouns.append(s.childNodes[0].nodeValue) for s in itemlist2: prons.append(s.childNodes[0].nodeValue) for s in itemlist3: adj.append(s.childNodes[0].nodeValue) for s in itemlist4: adv.append(s.childNodes[0].nodeValue) for s in itemlist5: verbs.append(s.childNodes[0].nodeValue) for s in itemlist6: conj.append(s.childNodes[0].nodeValue) def gettinPosLen18(): xmldoc = minidom.parse('L18.xml') itemlist1 = xmldoc.getElementsByTagName('noun') itemlist2 = xmldoc.getElementsByTagName('pron') itemlist3 = xmldoc.getElementsByTagName('adj') itemlist4 = xmldoc.getElementsByTagName('adv') itemlist5 = xmldoc.getElementsByTagName('verb') itemlist6 = xmldoc.getElementsByTagName('conj') for s in itemlist1: nouns.append(s.childNodes[0].nodeValue) for s in itemlist2: prons.append(s.childNodes[0].nodeValue) for s in itemlist3: adj.append(s.childNodes[0].nodeValue) for s in itemlist4: adv.append(s.childNodes[0].nodeValue) for s in itemlist5: verbs.append(s.childNodes[0].nodeValue) for s in itemlist6: conj.append(s.childNodes[0].nodeValue) def gettinPosLen19(): xmldoc = minidom.parse('L19.xml') itemlist1 = xmldoc.getElementsByTagName('noun') itemlist2 = xmldoc.getElementsByTagName('pron') itemlist3 = xmldoc.getElementsByTagName('adj') itemlist4 = xmldoc.getElementsByTagName('adv') itemlist5 = xmldoc.getElementsByTagName('verb') itemlist6 = xmldoc.getElementsByTagName('conj') for s in itemlist1: nouns.append(s.childNodes[0].nodeValue) for s in itemlist2: prons.append(s.childNodes[0].nodeValue) for s in itemlist3: adj.append(s.childNodes[0].nodeValue) for s in itemlist4: adv.append(s.childNodes[0].nodeValue) for s in itemlist5: verbs.append(s.childNodes[0].nodeValue) for s in itemlist6: conj.append(s.childNodes[0].nodeValue) def gettinPosLen20(): xmldoc = minidom.parse('L20.xml') itemlist1 = xmldoc.getElementsByTagName('noun') itemlist2 = xmldoc.getElementsByTagName('pron') itemlist3 = xmldoc.getElementsByTagName('adj') itemlist4 = xmldoc.getElementsByTagName('adv') itemlist5 = xmldoc.getElementsByTagName('verb') itemlist6 = xmldoc.getElementsByTagName('conj') for s in itemlist1: nouns.append(s.childNodes[0].nodeValue) for s in itemlist2: prons.append(s.childNodes[0].nodeValue) for s in itemlist3: adj.append(s.childNodes[0].nodeValue) for s in itemlist4: adv.append(s.childNodes[0].nodeValue) for s in itemlist5: verbs.append(s.childNodes[0].nodeValue) for s in itemlist6: conj.append(s.childNodes[0].nodeValue) gettinNouns() gettinPosLen2() gettinPosLen3() gettinPosLen4() gettinPosLen5() gettinPosLen6() gettinPosLen7() gettinPosLen8() gettinPosLen9() gettinPosLen10() gettinPosLen11() gettinPosLen12() gettinPosLen13() gettinPosLen14() gettinPosLen15() gettinPosLen16() gettinPosLen17() gettinPosLen18() gettinPosLen19() gettinPosLen20() gettinProns() gettinVerbs() class pos: def posTagging(self,j): global prons,adj,adv,conj,verbs if j not in prons: if j not in adj: if j not in adv: if j not in conj: if j not in verbs: return (j,"noun") else: return(j,"verb") else: return (j,"conj") else: return (j,"adv") else: return (j,"adj") else: return (j,"pron") # a=pos() # sent = u'কেমন আছেন' # sent = sent.split() # for w in sent: # print(a.posTagging(w))
ef8f21afbcc9782be8d477249df0b998601e6f75
Jonny-Full/CWI-Transmissivity
/data_to_csv.py
5,245
3.703125
4
# -*- coding: utf-8 -*- """ This module was created to hold any code that transforms our data into csv files. This module has two functions: Functions ----------- calculated_data_to_csv: This function take the data from transmissivity calculated and conductivity_calculated and converts the data into a csv file so the user can easily interact with the data. This file will also be used to create a feature class. calculated_data_statistics_csv: This function takes the .csv file created in calculated_data_to_csv and performes statistical analysis. This function then creates another .csv file for the user to interact with at their convienience. Author: Jonny Full Version: 9/31/2020 """ import numpy as np import pandas as pd def calculated_data_to_csv(transmissivity_calculated, conductivity_calculated, confirmed_wells, feature_class_name): """Converts the transmissivity, hydraulic conductivity, and well location data into a csv file. Parameters: ----------- transmissivity_calculated: list[float] transmissivity_calculated represents the calculated Transmissivity for each row in confirmed_wells. conductivity_calculated: list[float] conductivity_calculated represents the calculated hydraulic conductivity for each row intransmissivity_calculated. confirmed_wells: list[[list1][list2]] This is a list of all pertinant information required to plot the wells spacially and calculate Transmissivity. list1 = list[UTME (int), UTMN (int), AQUIFER (str), Screen Length (float), Casing Radius (ft), Relate ID (str)] list 2 = list[Pump Rate (float), Duration (float), Drawdown (float), Relate ID (str)] feature_class_name = string This is the name of the csv file. This is input by the user in GIS. Returns: -------- my_df: pandas dataframe A dataframe containing the location, transmissivities, and hydraulic conductivities for every well in our neighborhood. raw_csv_name: string The name of the csv file created. Notes: -------- This .csv file is dropped into the ArcGIS project in which they are running this script through. """ utm_e = [i[0][0] for i in confirmed_wells] utm_n = [i[0][1] for i in confirmed_wells] np.set_printoptions(suppress=True) #removes scientific notation location = np.array([utm_e, utm_n]) location = location.transpose() transmissivity_calculated = np.array(transmissivity_calculated) conductivity_calculated = np.array(conductivity_calculated) joined_data = np.concatenate((location, transmissivity_calculated, conductivity_calculated), axis = 1) my_df = pd.DataFrame(joined_data) header_list = ['UTME', 'UTMN', 'T_min', 'T_raw', 'T_max', 'K_min', 'K_raw', 'K_max', 'Well ID'] raw_csv_name = f"{feature_class_name}.csv" my_df.to_csv(raw_csv_name, index = False, header = header_list) return my_df, raw_csv_name def calculated_data_statistics_csv(my_df, feature_class_name): """Uses the data in my_df to create another csv file with statistical analysis. Each column will have the following items calculated, Count, Mean, Standard Deviation, Minimum, 25% Percentile, Median, 75% Percentile, Maximum, Logrithmic Mean, Logrithmic Standard Deviation. Parameters: ----------- my_df: pandas dataframe A dataframe containing the location, transmissivities, and hydraulic conductivities for every well in our neighborhood. feature_class_name = string This is the name of the csv file. This is input by the user in GIS. Notes: ------ This .csv file is dropped into the ArcGIS project in which they are running this script through. This .csv file also has the same primary name as the file created in calculated_data_to_csv. However, this file has _statistics attached to its file name. """ #remove Well ID and UTMs from dataframe updated_df = my_df.drop([0, 1, 8], axis = 1) raw_csv_name_stats = f"{feature_class_name}_statistics.csv" header_list = ["T_min", "T_raw", "T_max", "K_min", "K_raw", "K_max"] index_list = {0:'Count', 1:'Mean', 2:'Standard Deviation', 3:'Minimum', 4:'25th Percentile', 5:'Median', 6:'75th Percentile', 7:'Maximum', 8:'Logrithmic Mean', 9:'Logrithmic Standard Deviation'} log_mean = np.log10(updated_df.mean()) log_std = np.log10(updated_df.std()) useful_values = updated_df.describe() useful_values = useful_values.append(log_mean, ignore_index = True) useful_values = useful_values.append(log_std, ignore_index = True) useful_values = useful_values.rename(index = index_list) #gives the index unique names useful_values.to_csv(raw_csv_name_stats, header = header_list)
b92fe200fc7faa8bbe20f0a87e032d78000dc598
M4R14/mini-project-network
/gameXO.py
1,568
3.859375
4
import random board = [0,1,2, 3,4,5, 6,7,8] def show(): print board[0],'|',board[1],'|',board[2] print '---------' print board[3],'|',board[4],'|',board[5] print '---------' print board[6],'|',board[7],'|',board[8] def checkLine(char, spot1, spot2, spot3): if board[spot1] == char and board[spot2] == char and board[spot3] == char: # print board[spot1],':',board[spot2],':',board[spot3] return True def checkWin(char): if checkLine(char,0,1,2): return True if checkLine(char,3,4,5): return True if checkLine(char,6,7,8): return True if checkLine(char,0,3,6): return True if checkLine(char,1,4,7): return True if checkLine(char,2,5,8): return True if checkLine(char,0,4,8): return True if checkLine(char,2,4,6): return True show() while True: input = raw_input("Select a spot: ") input = int(input) if board[input] != 'X' and board[input] != 'O': board[input] = 'X' if checkWin('X') == True: show() print "~~ X WINS ~~" break; while True: random.seed() opponent = random.randint(0,8) if board[opponent] != 'O' and board[opponent] != 'X': board[opponent] = 'O' if checkWin('O') == True: show() print "~~ O WINS ~~" break; break; else: print 'This spot is taken!' show()
55ae7ae4ad64c690800e9d2a9d37684eb3069bb9
andkoc001/pands-problem-set
/06-secondstring.py
1,379
4.15625
4
# Title: Second Strig # Description: Solution to problem 6 - program that takes a user input string and outputs every second word. # Context: Programming and Scripting, GMIT, 2019 # Author: Andrzej Kocielski # Email: G00376291@gmit.ie # Date of creation: 10-03-2019 # Last update: 10-03-2019 ### # Prompt for the user; definition of a new variable "sentence" for the user's input # Intermediate test of the program - predefined sentence # sentence = "1abc 2def 3geh 4ijk 5lkm 6nop 7rst 8uwz" sentence = input("Please enter a sentence: ") # Intermediate test of the program - prints out the user's input # print(type(sentence)) # print(sentence) # Calls method split method in order to split the user input into single words, separated by a space sentence.split() # Assignment of number of words in the sentence to variable n n = len(sentence.split()) # Intermediate test of the program - shows number of words in the sentence # print(n) # Joining the words by contanation - pre-definintion of empty (for now) variable, which will be subsequently updated as the program runs result_line = "" # Prints out odd words from the sentence for i in range(n): # Separation of odd and even words if i % 2 == 0: # this was original command that returned words in separate lines # print(sentence.split()[i]) result_line += (sentence.split()[i]) + " " print(result_line)
721bac447024b95c310b6d18d62e24d6b552d491
thespacemanatee/10.009-ESCAPE-Text-RPG
/Submission/Modular Version/map.py
6,920
3.5625
4
##### MAP ##### """ a1 a2 a3 # PLAYER STARTS AT b2 ---------- | | | | a3 ---------- | | X| | b3 ---------- | | | | c3 ---------- """ LOCATION = '' DESCRIPTION = 'description' INSPECT = 'examine' SOLVED = False TASK = 'task' UP = 'up', 'north' DOWN = 'down', 'south' LEFT = 'left', 'west' RIGHT = 'right', 'east' MAP_DRAWING = None solved_places = {'a1': False, 'a2': False, 'a3': False, 'b1': False, 'b2': True, 'b3': False, 'c1': False, 'c2': False, 'c3': False, } zonemap = { 'a1': { LOCATION: "Winding Staircase", DESCRIPTION: 'You find yourself at the foot of a staircase leading towards... perhaps and exit?\n', INSPECT: 'Upon closer examination, there is a riddle inscribed on one of the railings!\n', TASK: "It reads, 'What two things can you never eat for breakfast?'\n", SOLVED: 'lunch and dinner', UP: 'a1', DOWN: 'b1', LEFT: 'a1', RIGHT: 'a2', MAP_DRAWING: '''---------- | X| | | ---------- | | | | ---------- | | | | ----------''' }, 'a2': { LOCATION: "Main Entrance", DESCRIPTION: 'You see the exit - but you do not have a key!\nThe door seems too big to kick down as well...\n', INSPECT: '', TASK: 'Looks like you cannot escape until you have explored all the other rooms...\nThe keyhole seems oddly shaped... you cannot think of any key that might fit this keyhole.\n', SOLVED: False, UP: 'a2', DOWN: 'b2', LEFT: 'a1', RIGHT: 'a3', MAP_DRAWING: '''---------- | | X| | ---------- | | | | ---------- | | | | ----------''' }, 'a3': { LOCATION: "Kitchen", DESCRIPTION: 'A musty smell filled the air - this kitchen must have been left alone for years...\n', INSPECT: 'A goblin-esque creature slumbers out of its corner - much to your surprise - and motions you closer.\n', TASK: "'A riddle - you must answer, if it is escape - you desire. Ooohooohoo yesh.'\n'David's father has three sons : Tom, Dick and _____. '\n", SOLVED: 'david', UP: 'a3', DOWN: 'b3', LEFT: 'a2', RIGHT: 'a3', MAP_DRAWING: '''---------- | | | X| ---------- | | | | ---------- | | | | ----------''' }, 'b1': { LOCATION: "Master Bedroom ", DESCRIPTION: 'Whoever lived in this house must have been deranged.\nTorture equipment were strewn all over the room as you tip-toed across,\nmaking your way to the door on the opposite.\n', INSPECT: 'You notice a riddle written on the bedsheet in blood.\n', TASK: "What's a lifeguard's favorite game?\n", SOLVED: 'pool', UP: 'a1', DOWN: 'c1', LEFT: 'b1', RIGHT: 'b2', MAP_DRAWING: '''---------- | | | | ---------- | X| | | ---------- | | | | ----------''' }, 'b2': { LOCATION: 'Cell ', DESCRIPTION: 'You find yourself in a dank and musty cell.\n', INSPECT: 'You need to get out of this hell hole...\n', TASK: None, SOLVED: True, UP: 'a2', DOWN: 'c2', LEFT: 'b1', RIGHT: 'b3', MAP_DRAWING: '''---------- | | | | ---------- | | X| | ---------- | | | | ----------''' }, 'b3': { LOCATION: "Bathroom ", DESCRIPTION: 'You reek at the smell of fecal matter.\nSomeone must have forgotten to flush the toilet for seemingly... years.\n', INSPECT: 'The reflection in the mirror startles you. You could have sworn that your own reflection moved on its own accord.\n', TASK: "Suddenly the reflection asks you,\n'I am not alive, but I grow;\nI don't have lungs, but I need air;\nI don't have a mouth, but water kills me.\nWhat am I?\n", SOLVED: 'fire', UP: 'a3', DOWN: 'c3', LEFT: 'b2', RIGHT: 'b3', MAP_DRAWING: '''---------- | | | | ---------- | | | X| ---------- | | | | ----------''' }, 'c1': { LOCATION: "Dining Hall", DESCRIPTION: '''A strong pungent smell of rotting carcass wafts into your nose.\nYou are not alone here...\n\nA burly Troll lumbers towards you, getting ready to swing its club!\nYou have to KILL it or DIE trying!\n ░░░░▄▄▄▄▀▀▀▀▀▀▀▀▄▄▄▄▄▄ ░░░░█░░░░▒▒▒▒▒▒▒▒▒▒▒▒░░▀▀▄ ░░░█░░░▒▒▒▒▒▒░░░░░░░░▒▒▒░░█ ░░█░░░░░░▄██▀▄▄░░░░░▄▄▄░░░█ ░▀▒▄▄▄▒░█▀▀▀▀▄▄█░░░██▄▄█░░░█ █▒█▒▄░▀▄▄▄▀░░░░░░░░█░░░▒▒▒▒▒█ █▒█░█▀▄▄░░░░░█▀░░░░▀▄░░▄▀▀▀▄▒█ ░█▀▄░█▄░█▀▄▄░▀░▀▀░▄▄▀░░░░█░░█ ░░█░░▀▄▀█▄▄░█▀▀▀▄▄▄▄▀▀█▀██░█ ░░░█░░██░░▀█▄▄▄█▄▄█▄████░█ ░░░░█░░░▀▀▄░█░░░█░███████░█ ░░░░░▀▄░░░▀▀▄▄▄█▄█▄█▄█▄▀░░█ ░░░░░░░▀▄▄░▒▒▒▒░░░░░░░░░░█ ░░░░░░░░░░▀▀▄▄░▒▒▒▒▒▒▒▒▒▒░█ ░░░░░░░░░░░░░░▀▄▄▄▄▄░░░░░█''', INSPECT: 'examine', TASK: 'task', SOLVED: 'solved', UP: 'b1', DOWN: 'c1', LEFT: 'c1', RIGHT: 'c2', MAP_DRAWING: '''---------- | | | | ---------- | | | | ---------- | X| | | ----------''' }, 'c2': { LOCATION: "Unknown", DESCRIPTION: 'The door infront of you is locked.\n', INSPECT: 'Looks like you may have to resort to kicking it down.', TASK: 'task', SOLVED: None, UP: 'b2', DOWN: 'c2', LEFT: 'c1', RIGHT: 'c3', MAP_DRAWING: '''---------- | | | | ---------- | | | | ---------- | | X| | ----------''' }, 'c3': { LOCATION: "Altar", DESCRIPTION: '''The smell of incense burns your nose. Something demonic resides here...\n\nA Witch spawned out of nowhere and prepares to cast her spell!\nYou must KILL her or DIE trying!\n /\\ _/__\_ /( o\\ /| // \-' __ ( o, /\\ ) / | / _\\ >>>>==(_(__u---(___ )----- // /__)''', INSPECT: None, TASK: None, SOLVED: None, UP: 'b3', DOWN: 'c3', LEFT: 'c2', RIGHT: 'c3', MAP_DRAWING: '''---------- | | | | ---------- | | | | ---------- | | | X| ----------''' }, }
0474865bcab2bf2ee00e506cffa611d1a5220a42
culeJUN/BaekJoon
/07.문자열/07-04.py
143
3.53125
4
time = int(input()) for i in range(time) : num, s = input().split() for i in s : print(i * int(num), end = '') print()
de7395aa845bb9f39ade95d449fe3a5bf9c5f93a
culeJUN/BaekJoon
/10.재귀/10-02.py
151
3.71875
4
def fibo (i) : if i == 0 : return 0 if i == 1 : return 1 return fibo(i - 1) + fibo(i - 2) x = int(input()) print(fibo(x))
fd138e19e420985a58e97501cc239e3e2bb13490
culeJUN/BaekJoon
/09.기본 수학 2/09-10.py
99
3.796875
4
import math r = float(input()) print('%0.6f' % float(r*r*math.pi)) print('%0.6f' % float(r*r*2))
f5b1056660c96894a31e82f852d8a666e0e6e661
czqzju/algorithms
/Interview Preparation Kit/Dynamic Programming/Abbreviation.py
1,027
3.734375
4
#!/bin/python3 import math import os import random import re import sys # Complete the abbreviation function below. def check(a, b): if len(b) > len(a): return False elif len(b) == len(a): if len(b) == 0 or b == a.upper(): return True else: return False else: if len(b) == 0: if a.lower() == a: return True else: return False else: if a[-1].isupper(): if a[-1] == b[-1]: return check(a[:-1], b[:-1]) else: return False else: return check(a[:-1] + a[-1].upper(), b) or check(a[:-1], b) def abbreviation(a, b): flag = check(a, b) if flag: return "YES" else: return "NO" if __name__ == '__main__': q = int(input()) for q_itr in range(q): a = input() b = input() result = abbreviation(a, b) print(result)
032eb3a8741d3be508427785106fdd1abb0b5a0a
czqzju/algorithms
/Graph Theory/Roads_in_HackerLand.py
2,452
3.515625
4
#!/bin/python3 #https://www.hackerrank.com/challenges/johnland/problem pypy3 import os import sys # # Complete the roadsInHackerland function below. def findParent(node, parent): while not node == parent[node]: node = parent[node] return parent[node] def updateParent(node, parent, p): while parent[node] != p: tmp = parent[node] parent[node] = p node = tmp def roadsInHackerland(n, roads): roads.sort(key = lambda road:road[2]) parent = [i for i in range(0, n)] numOfNodes = [1] * n edges = {} cntOfEdges = 0 for i in range(0, len(roads)): v1 = roads[i][0] - 1 v2 = roads[i][1] - 1 value = roads[i][2] if v1 in edges and v2 in edges: p1 = findParent(v1, parent) p2 = findParent(v2, parent) if p1 == p2: continue else: edges[v1][v2] = value edges[v2][v1] = value parent[p2] = p1 updateParent(v2, parent, p1) cntOfEdges += 1 elif v1 in edges and v2 not in edges: p1 = findParent(v1, parent) edges[v1][v2] = value edges[v2] = {v1: value} parent[v2] = p1 cntOfEdges += 1 elif v1 not in edges and v2 in edges: p2 = findParent(v2, parent) edges[v2][v1] = value edges[v1] = {v2: value} parent[v1] = p2 cntOfEdges += 1 else: edges[v1] = {v2 : value} edges[v2] = {v1 : value} parent[v2] = v1 cntOfEdges += 1 if cntOfEdges == n - 1: break q = [i for i in edges.keys() if len(edges[i]) == 1] dis = 0 while len(q): cur = q.pop() if len(edges[cur]) == 0: break for k, v in edges[cur].items(): dis += numOfNodes[cur] * (n - numOfNodes[cur]) * 2 ** v del edges[k][cur] numOfNodes[k] += numOfNodes[cur] if len(edges[k]) == 1: q.append(k) del edges[cur] return bin(dis)[2:] if __name__ == '__main__': # fptr = open(os.environ['OUTPUT_PATH'], 'w') nm = input().split() n = int(nm[0]) m = int(nm[1]) roads = [] for _ in range(m): roads.append(list(map(int, input().rstrip().split()))) result = roadsInHackerland(n, roads) print(result) # fptr.write(result + '\n') # # fptr.close()
bedb53f76cdcbe631f2511178429441760f6731d
MukulJuneja07/Python_files
/MultiThreading.py
301
3.609375
4
import threading x=0 y=0 def func1(): global x for i in range(100000000): x=x+1 def func2(): global y for i in range(100000000): y=y+1 Th1 = threading.Thread(target=func1) Th2 = threading.Thread(target=func2) Th1.start() Th2.start() Th1.join() Th2.join() print(x,y)
8b443f8883bf05a1d542d03c61a9f33f2e0496e6
MukulJuneja07/Python_files
/FactorsofNo.py
523
3.5625
4
x=int(input("Enter any number")) fac=1 for i in range(1,x+1): fac=fac*i print(fac) # # from netrc import netrc # n=int(input("Enter range for fibo series")) # x=0 # y=1 # print(x) # print(y) # next=0 # while(next<=n): # next=x+y # print(next) # x=y # y=next # print(next) # i=0 # x=0 # y=1 # while(i<10): # if(i<=1): # Next = i # else: # Next = x+y # x=y # y=Next # print(Next) # i=i+1 # x=0 # y=1 # u=x+y # while(u<50): # print(u) # u=u+y
1dc7162067d1497d393bec7d73920b5663f7bdfb
liwasai/MST
/1.py
1,315
3.8125
4
1.Python中pass语句的作用是什么? pass语句什么也不做,一般作为占位符或者创建占位程序,pass语句不会执行任何操作。 2.Python是如何进行类型转换的? Python提供了将变量或值从一种类型转换成另一种类型的内置函数。比如int函数能够将符合数学格式数字型字符串转换成整数。否则,返回错误信息。 3.Python是如何进行内存管理的? Python引用了一个内存池(memory pool)机制,即Pymalloc机制(malloc:n.分配内存),用于管理对小块内存的申请和释放。 4.dict 的 items() 方法与 iteritems() 方法的不同? items方法将所有的字典以列表方式返回,其中项在返回时没有特殊的顺序; iteritems方法有相似的作用,但是返回一个迭代器对象 5.什么是lambda函数?它有什么好处? 编程中提到的 lambda 表达式,通常是在需要一个函数,但是又不想费神去命名一个函数的场合下使用,也就是指匿名函数。 Python允许你定义一种单行的小函数。定义lambda函数的形式如下:labmda 参数:表达式lambda函数默认返回表达式的值。你也可以将其赋值给一个变量。lambda函数可以接受任意个参数,包括可选参数,但是表达式只有一个。
afb64292cd8438dcbcee167ac2d27ff275d84457
paul-madut/ISC3U-Unite3-04-Python
/number_comparer.py
563
4.09375
4
#!/usr/bin//env python3 # Created on: September 2019 # Created by: Paul Madut # This is the a program used as a random number generator def main(): # This function does plays a game # Input user_number = int(input("Give a number: ")) print(" ") # Process if user_number < 0: print("Your number is less than 0.") elif user_number == 0: print("Your number is 0") elif user_number > 0: print("Your number is bigger than 0") else: print("Bro ikd what to do") if __name__ == "__main__": main()
e68f38514b48634019920a756c58e84d22afdd27
abjose/misc
/maxflow.py
3,191
3.625
4
import math nodes = 0 # number of nodes CapMatrix = None # capacity matrix FlowMatrix = None # flow matrix MaxFlow = 0 # flow to T nodeArray = [ ] pathList = [ ] usedList = [ ] def initialize(): global nodes global CapMatrix global FlowMatrix global MaxFlow print "Please enter the number of nodes, not including S and T" nodes = int(raw_input("Number of nodes: ")) nodes += 2 print "So, including S and T, there are " + str(nodes) + " nodes." print "\nNow will ask for connectivity of each node, forward flow only" print "Remember that 0 = S and " + str(nodes-1) + " = T." print "Enter a -1 if you want to pass on to the next node" CapMatrix = [[0 for i in range(nodes)] for j in range(nodes)] FlowMatrix = [[0 for i in range(nodes)] for j in range(nodes)] #CapMatrix[1][2] = 4 tempCap = 0 for x in range(nodes): while True: tempConn = int(raw_input("Node " + str(x) + " flows to node: ")) if (tempConn == -1): print "going to next node..." break # if NaN if (tempConn >= nodes): print "out of range! continuing..." continue tempCap = int(raw_input("With capacity: ")) print "Alright, updating matrix...\n" CapMatrix[x][tempConn] = tempCap def FindNMPHandler(): global nodes global CapMatrix global FlowMatrix global MaxFlow global nodeArray global startNode global pathList global usedList count = 1000000 while count > 0: FindNMP(0, [ ]) for path in pathList: print path usedList.append(path) AugmentPath(path) pathList = [ ] break count -= 1 #print count return True def FindNMP(x, array): global nodes global CapMatrix global FlowMatrix global pathList global usedList #find a non-max path if abs(x) == nodes-1: if usedList.count(array) == 0: pathList.append(array) print array return for k in range(1,nodes): #print "\n\ncalled again - x,k = " + str(x) + "," + str(k) if k == x or array.count(k) != 0: continue if CapMatrix[x][k] != 0 and IsNonMax(x,k): array.append(k) FindNMP(k, array) #return -1 elif CapMatrix[k][x] != 0 and FlowMatrix[k][x] > 0: array.append(k*-1) FindNMP(k, array) #return -1 #print "returned none\n" return None # nothing found :( def IsNonMax(x,y): global nodes global CapMatrix global FlowMatrix global MaxFlow if CapMatrix[x][y] > FlowMatrix[x][y]: return True return False def AugmentPath(path): global nodes global CapMatrix global FlowMatrix global MaxFlow # first, find max flow increase prevNode = 0 minVal = 99999 for node in path: absNode = abs(node) if node > 0: val = CapMatrix[prevNode][absNode] if node < 0: val = CapMatrix[absNode][prevNode] if val <= minVal: minVal = val prevNode = node prevNode = 0 for node in path: absNode = abs(node) if node > 0: val = FlowMatrix[prevNode][absNode] val += minVal FlowMatrix[prevNode][absNode] = val if node < 0: val = FlowMatrix[absNode][prevNode] val -= minVal FlowMatrix[absNode][prevNode] = val prevNode = node MaxFlow += minVal initialize() FindNMPHandler() print "done?" print "MaxFlow = " + str(MaxFlow) print "Flow matrix: " print FlowMatrix
70e3141a254c254d933e6bba2cae77e73ec03822
abjose/misc
/stuff.py
3,091
3.71875
4
def dissimilarity(s1, s2): # return dissimilarity of two strings assert len(s1) == len(s2) return sum([1 if s1[i]!=s2[i] else 0 for i in range(len(s1))]) def compare_substrings(n, s1, s2): # given two substrings, find all similar-enough matches without shifts assert len(s1) == len(s2) if n > len(s1): return [(s1, s2)] matches = [] i = 0 while i + n - 1 < len(s1): if dissimilarity(s1[i:i+n], s2[i:i+n]) < n: matches.append((s1[i:i+n], s2[i:i+n])) i += 1 return matches def compare_substrings_N(N, s1, s2): matches = [] for n in range(N+1): print s1, s2 matches += compare_substrings(n, s1, s2) return matches def similar_strings(N, S): # find substrings that are less than N dissimilar from each other in S offset = len(S) - N matches = [] while offset >= 0: s1 = S[:len(S)-offset] s2 = S[offset:] matches += compare_substrings_N(N, s1, s2) offset -= 1 return matches def k_palindrome(S, k): # SHOULD DO SOMETHING WITH EDIT-DISTANCE INSTEAD # return True if S is a k-palindrome (can be palindrome if remove at most k # characters return helper(S, k, 0, len(S)-1) def helper(S, k, head, tail): # recursive helper function if head >= tail: return True if k < 0: return False if S[head] == S[tail]: return helper(S, k, head+1, tail-1) if S[head] != S[tail]: return helper(S, k-1, head, tail-1 ) or helper(S, k-1, head+1, tail) def magazine_string(S, M): # see if can construct string S from character in string M mag_dict = dict() mag_pointer = 0 str_pointer = 0 while True: str_char = S[str_pointer] mag_char = M[mag_pointer] print str_char, mag_char if str_char == mag_char: # if both equal, don't need to do anything - just move on str_pointer += 1 mag_pointer += 1 elif str_char in mag_dict.keys() and mag_dict[str_char] > 0: # if we've already seen this character, 'use' it mag_dict[str_char] -= 1 str_pointer += 1 else: # if we haven't already seen the character, keep looking if mag_char in mag_dict.keys(): mag_dict[mag_char] += 1 else: mag_dict[mag_char] = 1 mag_pointer += 1 # check for termination conditions. Make sure to check str first. if str_pointer >= len(S): return True if mag_pointer >= len(M): return False def check_substring(sub, string): # see if sub is a substring of string # shouldn't go through _every_ substring in string, just until it find right # one... return any([sub==string[i:i+len(sub)] for i in range(len(string)-len(sub)+1)]) if __name__ == '__main__': #print similar_strings(1, "hiphop") #print k_palindrome("aaaaasaaaaaaaas", 2) #print magazine_string("holere", "hello there") print check_substring("bat", "abate")
a73453b34e88c4142ee0b676303553e307913987
kirigaikabuto/distancelesson2
/lesson4/12.py
787
3.734375
4
s="Привет меня зовут Ерасыл мне 22.Я живу в городе Алматы.Алматы построили в 18 веке" # 1) делим по точкам ["Привет Привет зовут Ерасыл мне 22","Я живу в городе Алматы","Алматы построили в 18 веке"] # 2) делим по пробелам одновременно все закидывать в общий массив # 3) ['Привет','Привет'....'живу'] # 4) разбирать на числа и слова preds = s.split(".") words=[] for i in preds: preds_words = i.split(" ") words=words+preds_words numbers=[] slova=[] for i in words: if i.isalpha(): slova.append(i) elif i.isdigit(): numbers.append(i) print(numbers) print(slova)
4fd102d6b6b48cadd7bcd5d89b8ac9c6fedb3395
kirigaikabuto/distancelesson2
/lesson12/5.py
324
3.625
4
from myutils import * persons=[ { "name":"yerassyl1", "year":1998 }, { "name":"yerassyl2", "year":1997 }, { "name":"yerassyl3", "year":1999 }, ] ages = list(map(getAge,persons)) # ages=[] # for i in persons: # realage = getAge(i) # ages.append(realage) print(ages)
b2b201f1e2f0bf41f056631465aaf22fcef33782
kirigaikabuto/distancelesson2
/lesson3/4.py
213
3.578125
4
arr=[] print(arr,len(arr)) arr.append(10) print(arr,len(arr)) arr.append(20) print(arr,len(arr)) arr.append(30) print(arr,len(arr)) arr.append(40) print(arr,len(arr)) sumi = arr[0]+arr[1]+arr[2]+arr[3] print(sumi)
d6a0b0eefc33cb07b658f265d86439b9b704ef23
kirigaikabuto/distancelesson2
/lesson3/17.py
395
4
4
# надо найти максимальный элемент массива # используя цикл for arr=[100,233,140,900] maxi=arr[0] n = len(arr) for i in range(n): if maxi<arr[i]: maxi=arr[i] print(maxi) # if maxi<arr[0]: # maxi = arr[0] # if maxi<arr[1]: # maxi = arr[1] # if maxi<arr[2]: # maxi = arr[2] # if maxi<arr[3]: # maxi = arr[3] # print(maxi)
366e59537c5d5373bf43ca909bbee2442e0e5502
kirigaikabuto/distancelesson2
/lesson6/7.py
192
3.578125
4
arr=[120,232,445,678] n = len(arr) # print(arr[0]) # print(arr[1]) # print(arr[2]) # print(arr[n-1]) for i in range(n): print(i,arr[i]) # for i in arr: # if i > 130: # print(i)
98c0c4525dd0bff2f7702c1388ce18e556c43c7f
kirigaikabuto/distancelesson2
/lesson7/11.py
212
3.5
4
# d={ # "name":"product1", # "price":1000 # } # print(d) # d['sale']=0.5 # d['name']="prdict12312" # print(d) product={} product['name']="sdsdd" product['price']=1000 product['price']=12300 print(product)
8cf25e3b49f99dac1527133b3789182424c4cdb0
kirigaikabuto/distancelesson2
/lesson2/9.py
81
3.78125
4
num = int(input()) if num==5 or num==10: print("OK") else: print("Error")
4635f47746cd281455ba2cce088f1a6f5de381b7
kirigaikabuto/distancelesson2
/lesson4/1.py
158
3.765625
4
s = "Hello world" #char #str много char n = len(s) # for i in range(n): # print(s[i]) # for i in s: # print(i) # s[0]="123" s = s+"Yerassyl" print(s)
df9b8f3cf31fb8797b7253807969324ba9142416
kirigaikabuto/distancelesson2
/lesson2/6.py
342
3.890625
4
# 0<=summa<50000 1.3 # 50000<=summa<100000 1.6 # 100000<=summa<150000 1.9 summa = int(input()) percent=0.0 if summa>=0 and summa<50000: percent = 1.3 elif summa>=50000 and summa<100000: percent = 1.6 elif summa>=100000 and summa<150000: percent = 1.9 else: print("Error") total_sum = summa+summa*percent/100 print(total_sum)
95d97d25e6298ae09a5f5892537dcdb4b7151358
utep-cs-systems-courses/os-shell-seanraguilar
/shell/myPipe.py
1,616
3.828125
4
import os from myRedirect import redirect from shell import executeCommands import pipe '''This is the pipes method that take output of one method as input of another for example: output | input''' def pipeInput(args): left = args[0:args.index("|")] # This gets data of left side of pipe right = args[len(left)+1:] # This will get the data of right side of pipe pRead, pWrite = os.pipe() # This is making the read and write rc = os.fork() # This creates a child process if rc < 0:# if the returns a 0 the for failed os.write(2, ("Fork has failed returning now %d\n" %rc).encode())# sys.exit(1)# This is used to exit elif rc == 0: # if return value is 0 do the following os.close(1) # This will close file descriptor 1 os.dup(pWrite) # This copies the file descriptors of the child and put into pipeWrite os.set_inheritable(1,True) for fd in (pRead,pWrite): os.close(fd) # This closes all the file descriptors executeCommands(left) # This inputs the left argument into executeCommands else: os.close(0) # This closes file descriptor 0 os.dup(pRead) # Then copies the files descriptor of the parent and puts it into pRead os.set_inheritable(0,True) for fd in (pWrite, pRead): os.close(fd) # This closes file descriptors in both pRead,pWrite if "|" in right: # if it finds '|' on the right side of argument then it pipes right vars pipe(right) # Then goes into pipe executeCommands(right) # The inputs the right argument executeCommands
b9997d5c2b81bd243fb326d6a24ea227ab6d1503
mkrug6/Examining-Enron-Emails-Using-Machine-Learning-Techniques
/analyze.py
1,217
3.734375
4
def analyze(data): """ Let's take a deeper look into the data """ persons = data.keys() POIs = filter(lambda person: data[person]['poi'], data) print('List of All People in the Data: ') print(', '.join(persons)) print('') print('Total Number of People:', len(persons)) print('') print('Number of POIs in the Dataset:', len(POIs)) print('') print('List of each individual POIs:', ', '.join(POIs)) print('') def fix(data): """ Fixes data points by performing replacements """ # Replace NaN values for zeros ff = [ 'salary', 'deferral_payments', 'total_payments', 'loan_advances', 'bonus', 'restricted_stock_deferred', 'deferred_income', 'total_stock_value', 'expenses', 'exercised_stock_options', 'other', 'long_term_incentive', 'restricted_stock', 'director_fees', 'from_poi_to_this_person', 'from_this_person_to_poi', 'to_messages', 'from_messages' ] for f in ff: for person in data: if data[person][f] == 'NaN': data[person][f] = 0 return data
3cc0fcee11a7eea3411f26afebac5fea6eebd6b1
BlackJimmy/SYSU_QFTI
/mateig.py
427
4.15625
4
#this example shows how to compute eigen values of a matrix from numpy import * #initialize the matrix n = 5 a = zeros( (n, n) ) for i in range(n): a[i][i] = i if(i>0): a[i][i-1] = -1 a[i-1][i] = -1 #print the matrix print "The matrix is:" for i in range(n): print a[i] #compute the eigen values of the matrix (eigvalues, eigvectors) = linalg.eig(a) print "Its eigen values are:" print eigvalues
2312bec70f516192b18b7e65848770283c15ef7a
Doyun-lab/codeup
/codeup_1156.py
111
3.6875
4
def distinct(x): if x % 2 == 0: return "even" else: return "odd" print(distinct(3)) print(distinct(4))
89a737abdb4b1c44fdb2dd2243d034d8069139bf
Nnett0523/PYMI_Ex
/ex7_4.py
1,330
3.59375
4
#!/usr/bin/env python3 def solve(text): '''Thực hiện biến đổi input: [a, abbbccccdddd, xxyyyxyyx] output: [a, abb3cc4dd4, xx2yy3xyy2x] Giải thích: Những chữ cái không lặp lại thì output giữ nguyên chữ cái đó. Những chữ cái liên tiếp sẽ in ra 2 lần + số lần lặp lại liên tiếp. Đây là một biến thể của một thuật toán nén dữ liệu có tên Run-length encoding (RLE). ''' result = None # Xoá dòng sau và viết code vào đây set các giá trị phù hợp result = '' text += '\n' # them de tranh mat thang d if len(text) < 2: result = text else: temp = text[0] # a count = 1 # a : 1 for char in text[1:]: # bbbccccdddd if char != temp: # d != c if count == 1: # a result += temp # a temp = char # b # continue elif count > 1: result += temp*2 + str(count) # a + bb3 + cc4 temp = char # d count = 1 # d:1 else: # d4 count += 1 return result def main(): print(solve('xxyyyxyyx')) if __name__ == "__main__": main()
659bfbd1e43478b563d20646b9a0517536635911
nestordemeure/flaxOptimizersBenchmark
/flaxOptimizersBenchmark/training_loop/tools/dict_arithmetic.py
3,347
4.03125
4
import copy import numbers import math #---------------------------------------------------------------------------------------- # HIGHER ORDER FUNCTIONS def map_dict(d, func): """ applies func to all the numbers in dict """ for (name,value) in d.items(): if isinstance(value, numbers.Number): d[name] = func(value) elif isinstance(value, list): for i in len(value): value[i] = func(value[i]) elif isinstance(value, dict): map_dict(value, func) #---------------------------------------------------------------------------------------- # UNARY OPERATIONS def zero_dict(d): """ creates a copy of d that is filled with zeroes """ def to_zero(x): return 0 if isinstance(x, int) else 0.0 result = copy.deepcopy(d) map_dict(result, to_zero) return result def divide_dict_scalar(d, denominator): """ divides all the elements in a dictionary by a given denominator """ map_dict(d, lambda x: x/denominator) def sqrt_dict(d): """ divides all the elements in a dictionary by a given denominator """ map_dict(d, math.sqrt) #---------------------------------------------------------------------------------------- # MULTIARY OPERATIONS def add_dict(d_out, d_in): """ adds d_in to d_out the sum is only applied to the numbers and list of numbers """ for (name,value_out) in d_out.items(): if isinstance(value_out, numbers.Number): d_out[name] += d_in[name] elif isinstance(value_out, list): value_in = d_in[name] for i in len(value_out): value_out[i] += value_in[i] elif isinstance(value_out, dict): add_dict(value_out, d_in[name]) def add_diff_square(d_out, d1, d2): """ computes d_out += (d1-d2)² the operation is only applied to the numbers and list of numbers """ for (name,value_out) in d_out.items(): if isinstance(value_out, numbers.Number): d_out[name] += (d1[name] - d2[name])**2 elif isinstance(value_out, list): value1 = d1[name] value2 = d2[name] for i in len(value_out): value_out[i] += (value1[i] - value2[i])**2 elif isinstance(value_out, dict): add_diff_square(value_out, d1[name], d2[name]) #---------------------------------------------------------------------------------------- # STATISTICS def average_dic(dict_list): """ computes the average of a list of dictionaries the average is only applied to the numbers and list of numbers """ result = copy.deepcopy(dict_list[0]) for d in dict_list[1:]: add_dict(result, d) divide_dict_scalar(result, len(dict_list)) return result def variance_dict(dict_list, average, unbiasing=-1): """ computes the variance of a list of dictionary, given their average """ result = zero_dict(average) for d in dict_list: add_diff_square(result, d, average) divide_dict_scalar(result, len(dict_list)+unbiasing) return result def standard_deviation_dict(dict_list, average): """ computes the standard deviation of a list of dictionary, given their average """ result = variance_dict(dict_list, average, unbiasing=-1.5) sqrt_dict(result) return result
82d2bbbc5b31db2f03c35db811650df07918a2b6
19rixo75/homeWork
/count_world_text.py
1,701
3.59375
4
# Домашнее задание: # Написать программу, которая открывает заданый пользователем файл, считает количество слов, и количество уникальных # слов (если это слово уже посчитанно, то второй раз не считает) # Примеры: # Программа = программа # Программа, = программа # Рыбачить и рыбачит это разные слова # Т.е. Знаки препинания в конце слова и регистр букв не должны влиять на уникальность # Результат записать в текстовый файл : название файла, количество слов, количество уникальных слов unic_word = input('Please enter word for search: \n--> ') with open('text_dir/text_1.txt', 'r', encoding='utf8') as read_file: file_content = read_file.read() file_content = file_content.replace(",", "").replace(":", "").replace("!", "").replace("?", "").replace(";", "").replace(".", "") word_content = len(file_content) count_word = file_content.count(unic_word) list_pr_tx = [read_file.name, word_content, count_word] header = ['Name_file', 'Unic_name', 'Count', 'Words'] with open('text_dir/info_text.txt', 'a', encoding='utf8') as write_file: write_file.write(header[0] + ' ' + header[1] + ' ' + header[2] + ' ' + header[3] + '\n') write_file.write(str(list_pr_tx[0]) + ' ' + unic_word + ' ' + str(list_pr_tx[2]) + ' ' + str(list_pr_tx[1]) + '\n')
7d06e324ef8334edbc2da72b12532772b55a7432
gogo7654321/python_gamer
/lower to upper in lists.py
204
4.09375
4
name = [] print ("enter 5 lowercase sentences and i will convert them to uppercase") for x in range (1,6): a = str(input()) name.append(a) for x in name: upper = (x.upper()) print(upper)
55d55eac8e4fc97d2ded50aeea233c4c568f562d
gogo7654321/python_gamer
/name to age.py
514
3.859375
4
while ("true") print ("enter any close family members name and I will figure out their age") name = str(input()) #print(name) if (name.lower() == 'sunny'): print ("you are 42 years old. That's really old!") if (name.lower() == 'devika'): print ("you are 36 years old. Thats decent age.") if (name.lower() == 'mira'): print ("you are way to young and the smallest brain in the family") if (name.lower() == 'neil' ): print (" you are 11 and the perfect age")
84cf0bb4403ac3a763b0d0c4f2f6b5bde775b447
chenjiahuan262821/LearnPy
/python_100_day/day16_sorting/temp.py
221
3.875
4
def Factorial(n): if n == 0 | n == 1: return 1 return Factorial(n-1)*n # print(Factorial(6)) def Fibonaqi(n): if n == 1: return 0 if n == 2: return 1 return Fibonaqi(n-1)+Fibonaqi(n-2) print(Fibonaqi(30))
a306575a2d00dc29c07aa7e14f5f1b86f6a67169
chenjiahuan262821/LearnPy
/python_100_day/day16_sorting/selectionSort.py
503
3.859375
4
''' 选择排序的算法 先设置minIndex为i,对应值为list[i] 然后从i+1开始往后遍历找出最小的值,并将minIndex设置为该值的位置 最后将i位置与minIndex位置的数值互换,就得到第i大的值 ''' a = [6,5,4,3,2,1,10,8,9,8.1] def selectionSort(list): for i in range(len(list)): minIndex = i for j in range(i+1, len(list)): if list[j] < list[minIndex]: minIndex = j list[i], list[minIndex] = list[minIndex], list[i] print(list) selectionSort(a)
2441f1675f6d6269601c6781bd7ff8d285d28402
chenjiahuan262821/LearnPy
/python_100_day/day9_class2/staticmethod.py
1,246
4.0625
4
from math import sqrt class Triangle(object): def __init__(self, a, b, c): self._a = a self._b = b self._c = c @staticmethod #静态方法,说明接下来的这个方法是绑定在类上的 def is_valid_static(a, b, c): return a + b > c and b + c > a and a + c > b #有效的话会返回True @classmethod #类方法,第一个参数约定名为cls,代表当前类相关的信息 def is_valid_class(cls, a, b, c): return a + b > c and b + c > a and a + c > b def perimeter(self): return self._a + self._b + self._c def area(self): half = self.perimeter() / 2 return sqrt(half * (half - self._a) * (half - self._b) * (half - self._c)) def main(): a, b, c = 6, 10, 6 if Triangle.is_valid_static(a, b, c): #静态方法是在给类发消息的时候调用的 t = Triangle(a, b, c) print(t.perimeter()) else: print('无法构成三角形') if Triangle.is_valid_class(a, b, c): #类方法是在给类发消息的时候调用的 t = Triangle(a, b, c) print(t.area()) else: print('无法构成三角形') #静态方法、类方法,都是绑定在类上的,但是对象也可以访问 print(t.is_valid_static(5,3,4)) print(t.is_valid_class(5,3,4)) if __name__ == '__main__': main()
0755dc776d103520af3d8d10fc16be3fe7b19d56
siots/analysis_noti_data
/parser_lib/csvhelper.py
12,606
3.5
4
#-*- coding: utf-8 -*- import csv,codecs import stdtable from datetime import datetime def csv_parser(filename, printable=False): csv_list = [] with open(filename, 'r') as csvfile: reader = csv.reader(csvfile) for row in reader: row_list=[] for col in row: if printable : if type(col) is unicode: print col.decode('utf-8').encode('utf-8'), '|', elif type(col) is str: print col, '|', if type(col) is unicode: row_list.append(col.decode('utf-8').encode('utf-8')) elif type(col) is str: row_list.append(col) if printable : print csv_list.append(row_list) return csv_list def export(std_table, filepath, csv_format): with codecs.open(filepath, 'w', encoding="utf8") as csvfile: csvfile.write(csv_format+'\n') for row in std_table: for col in row: # print col, type(col), type(datetime.now()), float if type(col) is type(datetime.now()): csvfile.write(str(col.strftime('%Y-%m-%d %H:%M:%S'))) elif type(col) is float or type(col) is int: csvfile.write(str(col)) elif type(col) is unicode: csvfile.write(col.replace(",", ",".decode("utf-8")).replace("\n", " ").replace("(", "[").replace(")", "]")) elif type(col) is None or col == None: csvfile.write(str(col)) elif type(col) is bool: csvfile.write(str(col)) else: csvfile.write(col.decode("utf-8").replace(",", ",".decode("utf-8")).replace("\n", " ").replace("(", "[").replace(")", "]")) csvfile.write(", ") csvfile.write('\n') def write_csvfile(csvfile, value): if type(value) is float or type(value) is int: csvfile.write(str(value)) elif type(value) is type(datetime.now()): csvfile.write(str(value.strftime('%Y-%m-%d %H:%M:%S'))) elif type(value) is unicode: csvfile.write(value.replace(",", ",".decode("utf-8")).replace("\n", " ").replace("(", "[").replace(")", "]")) else: csvfile.write(value.decode("utf-8").replace(",", ",".decode("utf-8")).replace("\n", " ").replace("(", "[").replace(")", "]")) def export_rank(std_table, filepath, printable = False): noti_rank_list = [] duration_rank_list = [] noti_response_rank_list = [] for row in stdtable: pass with codecs.open(filepath, 'w', encoding="utf8") as csvfile: csvfile.write() def export_std_dict(std_dict, filepath, printable=False): with codecs.open(filepath, 'w', encoding="utf8") as csvfile: if printable : print "count screen on : ", std_dict[stdtable.f_dict_screen_on] print "count screen unlock : ", std_dict[stdtable.f_dict_screen_unlock] print "-- list of running app after unlock and noti --" write_csvfile(csvfile, "0. 일일 unlock 횟수") csvfile.write(", ") write_csvfile(csvfile, std_dict[stdtable.f_dict_screen_unlock]) csvfile.write("\n") write_csvfile(csvfile, "1. 총 노티 갯수") csvfile.write(", ") write_csvfile(csvfile, std_dict[stdtable.f_dict_count_noti]) csvfile.write("\n") write_csvfile(csvfile, "2. noti - screen on : 노티로 화면이 켜진 횟수") csvfile.write(", ") write_csvfile(csvfile, std_dict[stdtable.f_dict_screen_on]) csvfile.write("\n") write_csvfile(csvfile, "3. noti - screen on - off: 노티 온 후 즉시 확인 못한 횟수") csvfile.write(", ") write_csvfile(csvfile, std_dict[stdtable.f_dict_screen_off]) csvfile.write("\n") # -------- list_of_dict = std_dict[stdtable.f_dict_list_run] sum_of_items = 0 limit_sec = 60 count_limit = 0 count_within_limit_list = [] count_over_limit_list = [] sum_of_items_under = 0 sum_of_items_over = 0 for row in list_of_dict: sum_of_items += row[1] if row[1] <= limit_sec: count_limit += 1 count_within_limit_list.append(row) sum_of_items_under += row[1] else: count_over_limit_list.append(row) sum_of_items_over += row[1] if printable: print "1)total count : ", len(list_of_dict), "avg : ", 0 if len(list_of_dict) == 0 else sum_of_items/len(list_of_dict) print "count under ", limit_sec, "seconds : ", count_limit print "-- end --" print "-- list of running app all of after noti -- " csvfile.write("\n") write_csvfile(csvfile, "4. noti - unlock - run@under 60s (screen off) : off시, 노티 온 후 즉시(60s) 앱 실행한 횟수") csvfile.write("\n") csvfile.write("\n") csvfile.write("1)total count , ") write_csvfile(csvfile, len(count_within_limit_list)) csvfile.write("\n") csvfile.write("2)interval avg , ") write_csvfile(csvfile, 0 if len(count_within_limit_list) == 0 else sum_of_items_under/len(count_within_limit_list)) csvfile.write("\n") csvfile.write("\n") csvfile.write("appname, interval(sec), noti time, app usage time, title, contents, app use durations\n") for row in count_within_limit_list: for col in row: if printable: print col, write_csvfile(csvfile, col) csvfile.write(", ") if printable: print "\n" csvfile.write("\n") csvfile.write("\n") write_csvfile(csvfile, "5. noti - unlock - run@over 60s (screen off) : off시, 노티 온 후 나중에 앱 실행한 횟수") csvfile.write("\n") csvfile.write("\n") csvfile.write("1)total count , ") write_csvfile(csvfile, len(count_over_limit_list)) csvfile.write("\n") csvfile.write("2)interval avg , ") write_csvfile(csvfile, 0 if len(count_over_limit_list) == 0 else sum_of_items_over/len(count_over_limit_list)) csvfile.write("\n") csvfile.write("\n") csvfile.write("appname, interval(sec), noti time, app usage time, title, contents, app use durations\n") sum_of_items = 0 for row in count_over_limit_list: for col in row: if printable: print col, write_csvfile(csvfile, col) csvfile.write(", ") sum_of_items += row[1] if printable: print "\n" csvfile.write("\n") list_of_dict = std_dict[stdtable.f_dict_list_run_on] sum_of_items = 0 limit_sec = 60 count_limit = 0 count_within_limit_list = [] count_over_limit_list = [] sum_of_items_under = 0 sum_of_items_over = 0 for row in list_of_dict: sum_of_items += row[1] if row[1] <= limit_sec: count_limit += 1 count_within_limit_list.append(row) sum_of_items_under += row[1] else: count_over_limit_list.append(row) sum_of_items_over += row[1] if printable : print "1)total count : ", len(list_of_dict), "avg : ", 0 if len(list_of_dict) == 0 else sum_of_items/len(list_of_dict) print "count under ", limit_sec, "seconds : ", count_limit csvfile.write("\n") csvfile.write("\n") write_csvfile(csvfile, "6. noti - run@under 60s (screen on) : on시, 노티 온 후 즉시 앱 실행한 횟수") csvfile.write("\n") csvfile.write("\n") csvfile.write("1)total count , ") write_csvfile(csvfile, len(count_within_limit_list)) csvfile.write("\n") csvfile.write("2)interval avg , ") write_csvfile(csvfile, 0 if len(count_within_limit_list) == 0 else sum_of_items_under/len(count_within_limit_list)) csvfile.write("\n") csvfile.write("\n") csvfile.write("appname, interval(sec), noti time, app usage time, title, contents, app use durations\n") for row in count_within_limit_list: for col in row: if printable: print col, write_csvfile(csvfile, col) csvfile.write(", ") if printable: print "\n" csvfile.write("\n") csvfile.write("\n") write_csvfile(csvfile, "7. noti - run@over 60s (screen on) : on시, 노티 온 후 나중에 앱 실행한 횟수") csvfile.write("\n") csvfile.write("\n") csvfile.write("1)total count , ") write_csvfile(csvfile, len(count_over_limit_list)) csvfile.write("\n") csvfile.write("2)interval avg , ") write_csvfile(csvfile, 0 if len(count_over_limit_list) == 0 else sum_of_items_over/len(count_over_limit_list)) csvfile.write("\n") csvfile.write("\n") csvfile.write("appname, interval(sec), noti time, app usage time, title, contents, app use durations\n") sum_of_items = 0 for row in count_over_limit_list: for col in row: if printable: print col, write_csvfile(csvfile, col) csvfile.write(", ") sum_of_items += row[1] if printable: print "\n" csvfile.write("\n") list_of_dict = std_dict[stdtable.f_dict_list_run_all] sum_of_items = 0 limit_sec = 60 count_limit = 0 count_within_limit_list = [] count_over_limit_list = [] sum_of_items_under = 0 sum_of_items_over = 0 for row in list_of_dict: sum_of_items += row[1] if row[1] <= limit_sec: count_limit += 1 count_within_limit_list.append(row) sum_of_items_under += row[1] else: count_over_limit_list.append(row) sum_of_items_over += row[1] if printable : print "1)total count : ", len(list_of_dict), "avg : ", 0 if len(list_of_dict) == 0 else sum_of_items/len(list_of_dict) print "count under ", limit_sec, "seconds : ", count_limit csvfile.write("\n") csvfile.write("\n") write_csvfile(csvfile, "8. noti-run@under 60s (screen on, off 전체) : on/off시, 노티 온 후 즉시 앱 실행한 횟수") csvfile.write("\n") csvfile.write("\n") csvfile.write("1)total count , ") write_csvfile(csvfile, len(count_within_limit_list)) csvfile.write("\n") csvfile.write("2)interval avg , ") write_csvfile(csvfile, 0 if len(count_within_limit_list) == 0 else sum_of_items_under/len(count_within_limit_list)) csvfile.write("\n") csvfile.write("\n") csvfile.write("appname, interval(sec), noti time, app usage time, title, contents, app use durations\n") for row in count_within_limit_list: for col in row: if printable: print col, write_csvfile(csvfile, col) csvfile.write(", ") if printable: print "\n" csvfile.write("\n") csvfile.write("\n") write_csvfile(csvfile, "9. noti-run@over 60s (screen on, off 전체) : on/off시, 노티 온 후 나중에 앱 실행한 횟수") csvfile.write("\n") csvfile.write("\n") csvfile.write("1)total count , ") write_csvfile(csvfile, len(count_over_limit_list)) csvfile.write("\n") csvfile.write("2)interval avg , ") write_csvfile(csvfile, 0 if len(count_over_limit_list) == 0 else sum_of_items_over/len(count_over_limit_list)) csvfile.write("\n") csvfile.write("\n") csvfile.write("appname, interval(sec), noti time, app usage time, title, contents, app use durations\n") for row in count_over_limit_list: for col in row: if printable: print col, write_csvfile(csvfile, col) csvfile.write(", ") if printable: print "\n" csvfile.write("\n")
f9af5624fe12b3c6bd0c359e5162b7f9f48234e7
Yarin78/yal
/python/yal/fenwick.py
1,025
3.765625
4
# Datastructure for storing and updating integer values in an array in log(n) time # and answering queries "what is the sum of all value in the array between 0 and x?" in log(n) time # # Also called Binary Indexed Tree (BIT). See http://codeforces.com/blog/entry/619 class FenwickTree: def __init__(self, exp): '''Creates a FenwickTree with range 0..(2^exp)-1''' self.exp = exp self.t = [0] * 2 ** (exp+1) def query_range(self, x, y): '''Gets the sum of the values in the range [x, y)''' return self.query(y) - self.query(x) def query(self, x, i=-1): '''Gets the sum of the values in the range [0, x).''' if i < 0: i = self.exp return (x&1) * self.t[(1<<i)+x-1] + self.query(x//2, i-1) if x else 0 def insert(self, x, v, i=-1): '''Adds the value v to the position x''' if i < 0: i = self.exp self.t[(1<<i)+x] += v return self.t[(1<<i)+x] + (self.insert(x//2, v, i-1) if i > 0 else 0)
d7d9550e9acb11727564ba122a9427139f47a5e3
ode2020/bubble_sort.py
/bubble.py
388
4.1875
4
def bubble_sort(numbers): for i in range (len(numbers) - 1, 0, -1): for j in range (i): if numbers[j] > numbers[j+1]: temp = numbers[j] numbers[j] = numbers[j+1] numbers[j+1] = temp print(numbers) numbers = [5, 3, 8, 6, 7, 2] bubble_sort(numbers) print(numbers) print("The code executed successfully")
a22b933bbaf3e12d053af0f4dc750c9b0d1338ed
zhaoyangkun/python-eight-sort
/heap_sort.py
1,264
3.78125
4
def adjust(arr, parent, n): """ 调整二叉树 :param arr: 列表 :param parent: 父节点下标 :param n: 列表长度 """ temp = arr[parent] # 保存父结点的值 child = 2 * parent + 1 # child 指向左孩子 while child < n: if child + 1 < n and arr[child] < arr[child + 1]: # 若右孩子存在且大于左孩子,将 child 指向右孩子 child += 1 if temp > arr[child]: # 父结点已大于左右孩子,结束循环 break arr[parent] = arr[child] # 把孩子结点的值赋给父结点 parent = child # 选取孩子结点的左孩子,继续进行调整 child = 2 * parent + 1 arr[parent] = temp def heap_sort(arr): """ 堆排序 :param arr: 列表 """ length = len(arr) # 循环建立初始大顶堆 for i in range((length - 1) // 2, -1, -1): adjust(arr, i, length) # n - 1 次循环,完成堆排序 for j in range(length - 1, 0, -1): arr[0], arr[j] = arr[j], arr[0] # 交换第一个元素和最后一个元素 adjust(arr, 0, j) # 对剩余的 j - 1 个元素进行调整 if __name__ == '__main__': a = [1, 3, 4, 5, 2, 6, 9, 7, 8, 0] heap_sort(a) print(a)
2a7cb0cb80e8207467f586bcba29401ed2e71840
Romumrn/Pipeline_variant_RDP
/script/.docker_modules/csv_checkdesign_python/0.0.1/check_design_chip_quant.py
2,465
3.65625
4
#!/usr/bin/env python3 import sys design=sys.argv[1] ## input csv file design_checked=sys.argv[2] ## output csv file: same as design input but make sure there is no space in the row ## avoid error in nextflow process def csv_parser(csv, csv_out): ERROR_STR = 'ERROR: Please check design file\n' def check_line_format(lspl): ## CHECK VALID NUMBER OF COLUMNS PER SAMPLE numCols = len(lspl) if numCols not in [4]: print (f"{ERROR_STR}Invalid number of columns (should be 4)!\nLine: {lspl}\nWARN: Colomn separator must be \t") sys.exit(1) IP_w,WCE_w,IP_m,WCE_m = lspl[0],lspl[1],lspl[2],lspl[3] if str(IP_w)==str(IP_m) or str(WCE_w)==str(WCE_m) or str(IP_w)==str(WCE_w) or str(IP_m)==str(WCE_m) or str(IP_w)==str(WCE_m) or str(WCE_w)==str(IP_m) : print (f"{ERROR_STR}Same file specified multiple times on line:\n {lspl}\n") sys.exit(1) return IP_w,WCE_w,IP_m,WCE_m HEADER = ['IP_w', 'WCE_w','IP_m','WCE_m'] header = csv.readline().strip().split('\t') if header != HEADER: print (f"{ERROR_STR} header:{header}!= {HEADER}\nWARN: Colomn separator must be \t") sys.exit(1) csv_out.write(f"IP_w\tWCE_w\tIP_m\tWCE_m\n") sampleMappingDict = {} for line in csv: line_sple = [elt.strip() for elt in line.strip().split("\t")] IP_w,WCE_w,IP_m,WCE_m=check_line_format(line_sple) IP_w=str(IP_w) WCE_w=str(WCE_w) IP_m=str(IP_m) WCE_=str(WCE_m) ## CHECK UNICITY EXPERIMENT [IP_w,WCE_w,IP_m,WCE_m] exp=f"{IP_w};{WCE_w};{IP_m};{WCE_m}" #exp=str(str(IP_w)+";"+str(WCE_w)+";"+str(IP_m)+";"+str(WCE_m)) if exp not in sampleMappingDict: sampleMappingDict[exp]="" else: print (f"WARN: experiment specified multiple times, migth be an error!\nLine: {line_sple}") sys.exit(1) csv_out.write(f"{IP_w}\t{WCE_w}\t{IP_m}\t{WCE_m}\n") #csv_out.write(str(IP_w)+"\t"+str(WCE_w)+"\t"+str(IP_m)+"\t"+str(WCE_m)+"\n") return None if __name__ == "__main__": # execute only if run as a script try: design_f=open(design,'r') except IOError: print('Cannot open', design) exit() try: output_f=open(design_checked,'w') except IOError: print('Cannot open', design_checked) exit() csv_parser(design_f,output_f)
0dc21795e938f7dbfcd47124654d8a002a790a65
ravalrupalj/BrainTeasers
/Edabit/Get_Student_Top_Notes.py
1,025
3.53125
4
#Create a function that takes an list of student dictionaries and returns a list of their top notes. If student does not have notes then let's assume their top note is equal to 0. def get_student_top_notes(lst): ans=[] for i in lst: if len(i['notes'])>0: ans.append(max(i['notes'])) elif len(i['notes'])==0: ans.append(0) return ans print(get_student_top_notes([{"id": 1,"name": "Jacek", "notes": [5, 3, 4, 2, 5, 5]},{ "id": 2, "name": "Ewa", "notes": [2, 3, 3, 3, 2, 5] },{"id": 3, "name": "Zygmunt","notes": [2, 2, 4, 4, 3, 3]}])) #➞ [5, 5, 4] print((get_student_top_notes([{'id': 1, 'name': 'Max', 'notes': [1, 5]}, {'id': 2, 'name': 'Cary', 'notes': [0, 5]}, {'id': 3, 'name': 'Lexi', 'notes': [2, 0]}, {'id': 4, 'name': 'Joshua', 'notes': [1, 2, 2]}, {'id': 5, 'name': 'Hans', 'notes': [3, 4, 0, 5, 1]}, {'id': 6, 'name': 'Alfie', 'notes': [0, 0, 2, 1, 5]}, {'id': 7, 'name': 'Ralph', 'notes': [4, 3, 1, 1, 1]}])) ) #[5, 5, 2, 2, 5, 5, 4]
aa83f5258b80e1c403a25d30aeb96f2a8125ec73
ravalrupalj/BrainTeasers
/Edabit/Day 3.3.py
459
4.125
4
#Get Word Count #Create a function that takes a string and returns the word count. The string will be a sentence. #Examples #count_words("Just an example here move along") ➞ 6 #count_words("This is a test") ➞ 4 #count_words("What an easy task, right") ➞ 5 def count_words(txt): t = txt.split() return len(t) print(count_words("Just an example here move along")) print(count_words("This is a test")) print(count_words("What an easy task, right"))
f96d35fd8ba47fc92f17627291bde8a896d72f02
ravalrupalj/BrainTeasers
/Edabit/Classes_for_Fetching.py
570
3.890625
4
def check(d1, d2, k): d1= { "sky": "temple", "horde": "orcs", "people": 12, "story": "fine", "sun": "bright" } d2 = { "people": 12, "sun": "star", "book": "bad" } if k in d1.keys() and k in d2.keys(): if d1[k]==d2[k]: return True elif d1[k]!=d2[k]: return 'Not the same' else: return 'One\'s empty' print(check('dict_first', 'dict_second', "horde") ) #➞ "One"s empty" print(check('dict_first', 'dict_second', "people") ) #➞ True print(check('dict_first', 'dict_second', "sun") ) #➞ "Not the same"
9975f7dc75b81bbbe7cfdcd701f2e09335a3ce54
ravalrupalj/BrainTeasers
/Edabit/Emptying_the_values.py
1,532
4.4375
4
#Emptying the Values #Given a list of values, return a list with each value replaced with the empty value of the same type. #More explicitly: #Replace integers (e.g. 1, 3), whose type is int, with 0 #Replace floats (e.g. 3.14, 2.17), whose type is float, with 0.0 #Replace strings (e.g. "abcde", "x"), whose type is str, with "" #Replace booleans (True, False), whose type is bool, with False #Replace lists (e.g. [1, "a", 5], [[4]]), whose type is list, with [] #Replace tuples (e.g. (1,9,0), (2,)), whose type is tuple, with () #Replace sets (e.g. {0,"a"}, {"b"}), whose type is set, with set() #Caution: Python interprets {} as the empty dictionary, not the empty set. #None, whose type is NoneType, is preserved as None #Notes #None has the special NoneType all for itself. def empty_values(lst): l=[] for i in lst: if type(i)==int: l.append(0) elif type(i)==float: l.append(0.0) elif type(i)==str: l.append('') elif type(i)==bool: l.append(False) elif type(i)==list: l.append([]) elif type(i)==tuple: l.append(()) elif type(i)==set: l.append(set()) else: l.append(None) return l print(empty_values([1, 2, 3]) ) #➞ [0, 0, 0] print(empty_values([7, 3.14, "cat"]) ) #➞ [0, 0.0, ""] print(empty_values([[1, 2, 3], (1,2,3), {1,2,3}]) ) #➞ [[], (), set()] print(empty_values([[7, 3.14, "cat"]])) #➞ [[]] print(empty_values([None]) ) #➞ [None]
60a84a613c12d723ba5d141e657989f33930ab74
ravalrupalj/BrainTeasers
/Edabit/Powerful_Numbers.py
615
4.1875
4
#Powerful Numbers #Given a positive number x: #p = (p1, p2, …) # Set of *prime* factors of x #If the square of every item in p is also a factor of x, then x is said to be a powerful number. #Create a function that takes a number and returns True if it's powerful, False if it's not. def is_powerful(num): i=1 l=[] while i<=num: if num%i==0: l.append(i) i=i+1 return l print(is_powerful(36)) #➞ True # p = (2, 3) (prime factors of 36) # 2^2 = 4 (factor of 36) # 3^2 = 9 (factor of 36) print(is_powerful(27)) #➞ True print(is_powerful(674)) #➞ False #Notes #N/A
343894e3dc8546e4bfa0d70d8977f2e479b4a289
ravalrupalj/BrainTeasers
/Edabit/Wumbology.py
176
3.890625
4
#Create a function that flips M's to W's (all uppercase). #wumbo("I LOVE MAKING CHALLENGES") ➞ "I LOVE WAKING CHALLENGES" def wumbo(words): return words.replace('M','W')
bd0d3c9c1ac6c1923d86e7fe04013059fb85cbe5
ravalrupalj/BrainTeasers
/Edabit/Percentage_of_Box_filled.py
1,055
4.0625
4
#Percentage of Box Filled In #Create a function that calculates what percentage of the box is filled in. Give your answer as a string percentage rounded to the nearest integer. # Five elements out of sixteen spaces. #Only "o" will fill the box and also "o" will not be found outside of the box. #Don't focus on how much physical space an element takes up, pretend that each element occupies one whole unit (which you can judge according to the number of "#" on the sides). def percent_filled(lst): count=0 t=0 for i in lst: if ' ' in i: count=count+i.count(' ') t=t+i.count('o') if count==0: return '100%' return str(round(100*t/(count+t)))+'%' print(percent_filled(["###","#o#","###"])) print(percent_filled([ "####", "# #", "#o #", "####"]) ) #➞ "25%" # One element out of four spaces. print(percent_filled(["#######","#o oo #", "#######"])) #➞ "60%" # Three elements out of five spaces. print(percent_filled([ "######","#ooo #","#oo #", "# #", "# #","######"]) ) #➞ "31%"
4eaf4aa432c28ae542c7f85144ac2ceb843f875e
ravalrupalj/BrainTeasers
/Edabit/Count_Letters_in_a_Word.py
789
4.09375
4
#Count Letters in a Word Search #Create a function that counts the number of times a particular letter shows up in the word search. #You will always be given a list with five sub-lists. def letter_counter(lst,letter): count=0 for i in lst: count=count+i.count(letter) return count print(letter_counter([ ["D", "E", "Y", "H", "A", "D"], ["C", "B", "Z", "Y", "J", "K"], ["D", "B", "C", "A", "M", "N"], ["F", "G", "G", "R", "S", "R"], ["V", "X", "H", "A", "S", "S"]], "D")) #➞ 3 # "D" shows up 3 times: twice in the first row, once in the third row. print(letter_counter([ ["D", "E", "Y", "H", "A", "D"], ["C", "B", "Z", "Y", "J", "K"], ["D", "B", "C", "A", "M", "N"], ["F", "G", "G", "R", "S", "R"], ["V", "X", "H", "A", "S", "S"]], "H")) #➞ 2
4dd2faade46f718a07aeba94270ea71ff90b5996
ravalrupalj/BrainTeasers
/Edabit/Is_the_Number_Symmetrical.py
462
4.4375
4
#Create a function that takes a number as an argument and returns True or False depending on whether the number is symmetrical or not. A number is symmetrical when it is the same as its reverse. def is_symmetrical(num): t=str(num) return t==t[::-1] print(is_symmetrical(7227) ) #➞ True print(is_symmetrical(12567) ) #➞ False print(is_symmetrical(44444444)) #➞ True print(is_symmetrical(9939) ) #➞ False print(is_symmetrical(1112111) ) #➞ True
885a0a3ce15dbf2504dd24ce14552a4e245b3790
ravalrupalj/BrainTeasers
/Edabit/Big_Countries.py
1,652
4.53125
5
#Big Countries #A country can be said as being big if it is: #Big in terms of population. #Big in terms of area. #Add to the Country class so that it contains the attribute is_big. Set it to True if either criterea are met: #Population is greater than 250 million. #Area is larger than 3 million square km. #Also, create a method which compares a country's population density to another country object. Return a string in the following format: #{country} has a {smaller / larger} population density than {other_country} class Country: def __init__(self, name, population, area): self.name = name self.population = population self.area = area # implement self.is_big self.is_big = self.population > 250000000 or self.area > 3000000 def compare_pd(self, other): # code this_density = self.population / self.area other_density = other.population / other.area if this_density > other_density: s_or_l = 'larger' else: s_or_l = 'smaller' return self.name + ' has a ' + s_or_l + ' population density than ' + other.name australia = Country("Australia", 23545500, 7692024) andorra = Country("Andorra", 76098, 468) print(australia.is_big ) #➞ True print(andorra.is_big ) #➞ False andorra.compare_pd(australia) #➞ "Andorra has a larger population density than Australia" #Notes #Population density is calculated by diving the population by the area. #Area is given in square km. #The input will be in the format (name_of_country, population, size_in_km2), where name_of_country is a string and the other two inputs are integers.
a22a66ffd651519956fc0f1ea0eb087a4146e8dd
ravalrupalj/BrainTeasers
/Edabit/Loves_Me_Loves_Me.py
1,034
4.25
4
#Loves Me, Loves Me Not... #"Loves me, loves me not" is a traditional game in which a person plucks off all the petals of a flower one by one, saying the phrase "Loves me" and "Loves me not" when determining whether the one that they love, loves them back. #Given a number of petals, return a string which repeats the phrases "Loves me" and "Loves me not" for every alternating petal, and return the last phrase in all caps. Remember to put a comma and space between phrases. def loves_me(num): l=['Loves me','Loves me not'] final_l=[] add=l[0] for i in range(0,num): final_l.append(add) if final_l[-1]==l[0]: add=l[1] else: add=l[0] final_l[-1]=final_l[-1].upper() return ', '.join(final_l) print(loves_me(3)) #➞ "Loves me, Loves me not, LOVES ME" print(loves_me(6) ) #➞ "Loves me, Loves me not, Loves me, Loves me not, Loves me, LOVES ME NOT" print(loves_me(1)) #➞ "LOVES ME" #Notes #Remember to return a string. #he first phrase is always "Loves me".
c12d6b85fe5baa9391cb20b87f11b903161fbf1b
ravalrupalj/BrainTeasers
/Edabit/Fix_the_Error.py
530
3.953125
4
#Remove all vowels def remove_vowels(st): l=['a','e','i','o','u'] ls=[] for i in st: if i not in l: ls.append(i) return ''.join(ls) def remove_vowels(string): vowels = "aeiou" for vowel in vowels: string=string.replace(vowel, "", ) return string print(remove_vowels("ben") ) #➞ "bn" print(remove_vowels("hello") ) #➞ "hllo" # The "e" is removed, but the "o" is still there! print(remove_vowels("apple") ) #➞ "appl" # The "e" is removed, but the "a" is still there!
13b3a8a4d538ca1404902f5cc9d0d4cb5380f231
ravalrupalj/BrainTeasers
/Edabit/sum_of_even_numbers.py
698
4.1875
4
#Give Me the Even Numbers #Create a function that takes two parameters (start, stop), and returns the sum of all even numbers in the range. #sum_even_nums_in_range(10, 20) ➞ 90 # 10, 12, 14, 16, 18, 20 #sum_even_nums_in_range(51, 150) ➞ 5050 #sum_even_nums_in_range(63, 97) ➞ 1360 #Remember that the start and stop values are inclusive. def sum_even_nums_in_range(start, stop): count=0 for i in range(start,stop+1): if i%2==0: count=count+i return count #return sum(i for i in range(start, stop+1) if not i%2) print(sum_even_nums_in_range(10, 20) ) # 10, 12, 14, 16, 18, 20 print(sum_even_nums_in_range(51, 150) ) print(sum_even_nums_in_range(63, 97) )
7b59b568c79277f3cc78d138298452775574e14f
ravalrupalj/BrainTeasers
/Edabit/Combined.py
864
4.03125
4
#Combined Consecutive Sequence #Write a function that returns True if two lists, when combined, form a consecutive sequence. #The input lists will have unique values. #The input lists can be in any order. #A consecutive sequence is a sequence without any gaps in the integers, e.g. 1, 2, 3, 4, 5 is a consecutive sequence, but 1, 2, 4, 5 is not. def consecutive_combo(lst1, lst2): t=lst1+lst2 sort=sorted(t) s='' for each in sort: s=s+str(each) maximum=max(t) minimum=min(t) for i in range(minimum,maximum+1): if str(i) not in s: return False return True print(consecutive_combo([7, 4, 5, 1], [2, 3, 6]) ) #➞ True print(consecutive_combo([1, 4, 6, 5], [2, 7, 8, 9]) ) #➞ False print(consecutive_combo([1, 4, 5, 6], [2, 3, 7, 8, 10]) ) #➞ False print(consecutive_combo([44, 46], [45]) ) #➞ True
7801a9735e3d51e4399ee8297d719d86eb44bc58
ravalrupalj/BrainTeasers
/Edabit/Recursion_Array_Sum.py
440
4.15625
4
#Recursion: Array Sum #Write a function that finds the sum of a list. Make your function recursive. #Return 0 for an empty list. #Check the Resources tab for info on recursion. def sum_recursively(lst): if len(lst)==0: return 0 return lst[0]+sum_recursively(lst[1:]) print(sum_recursively([1, 2, 3, 4])) #➞ 10 print(sum_recursively([1, 2]) ) #➞ 3 print(sum_recursively([1]) ) #➞ 1 print(sum_recursively([]) ) #➞ 0
207c144e096524b8de5e6d9ca11ce5cb4969d8e1
ravalrupalj/BrainTeasers
/Edabit/Letters_Only.py
496
4.25
4
#Letters Only #Write a function that removes any non-letters from a string, returning a well-known film title. #See the Resources section for more information on Python string methods. def letters_only(string): l=[] for i in string: if i.isupper() or i.islower(): l.append(i) return ''.join(l) print(letters_only("R!=:~0o0./c&}9k`60=y") ) #➞ "Rocky" print(letters_only("^,]%4B|@56a![0{2m>b1&4i4")) #➞ "Bambi" print(letters_only("^U)6$22>8p).") ) #➞ "Up"
4fad5f1ab4362dbc1119d1f72a85d6c91abdfa8f
ravalrupalj/BrainTeasers
/Edabit/The_Fibonacci.py
368
4.3125
4
#The Fibonacci Number #Create a function that, given a number, returns the corresponding Fibonacci number. #The first number in the sequence starts at 1 (not 0). def fibonacci(num): a=0 b=1 for i in range(1,num+1): c=a+b a=b b=c return c print(fibonacci(3) ) #➞ 3 print(fibonacci(7)) #➞ 21 print(fibonacci(12)) #➞ 233
a04557bc33db1b02d40ccd9a7866e64eae63786c
ravalrupalj/BrainTeasers
/Edabit/Mini_Peaks.py
598
3.765625
4
#Mini Peaks #Write a function that returns all the elements in an array that are strictly greater than their adjacent left and right neighbors. def mini_peaks(lst): l=[] for i in range(1,len(lst)-1): if lst[i-1]<lst[i] and lst[i+1]<lst[i]: l.append(lst[i]) return l print(mini_peaks([4, 5, 2, 1, 4, 9, 7, 2])) #➞ [5, 9] print(mini_peaks([1, 2, 1, 1, 3, 2, 5, 4, 4])) #➞ [2, 3, 5] print(mini_peaks([1, 2, 3, 4, 5, 6])) #➞ [] #Notes #Do not count boundary numbers, since they only have one left/right neighbor. #If no such numbers exist, return an empty array.
5182829f043490134cb86a3962b07a791e7ae0cb
ravalrupalj/BrainTeasers
/Edabit/How_many.py
601
4.15625
4
#How Many "Prime Numbers" Are There? #Create a function that finds how many prime numbers there are, up to the given integer. def prime_numbers(num): count=0 i=1 while num: i=i+1 for j in range(2,i+1): if j>num: return count elif i%j==0 and i!=j: break elif i==j: count=count+1 break print(prime_numbers(10)) #➞ 4 # 2, 3, 5 and 7 print(prime_numbers(20)) #➞ 8 # 2, 3, 5, 7, 11, 13, 17 and 19 print(prime_numbers(30)) #➞ 10 # 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29
f07bfd91788707f608a580b702f3905be2bf201b
ravalrupalj/BrainTeasers
/Edabit/One_Button_Messagin.py
650
4.28125
4
# One Button Messaging Device # Imagine a messaging device with only one button. For the letter A, you press the button one time, for E, you press it five times, for G, it's pressed seven times, etc, etc. # Write a function that takes a string (the message) and returns the total number of times the button is pressed. # Ignore spaces. def how_many_times(msg): if len(msg)==0: return 0 current=msg[0] rest_of_string = msg[1:] char_int=ord(current)-96 return char_int+how_many_times(rest_of_string) print(how_many_times("abde")) # ➞ 12 print(how_many_times("azy")) # ➞ 52 print(how_many_times("qudusayo")) # ➞ 123
d9acdd4825dfd641d4eac7dd92d15b428b0e07f0
ravalrupalj/BrainTeasers
/Edabit/Iterated_Square_Root.py
597
4.5
4
#Iterated Square Root #The iterated square root of a number is the number of times the square root function must be applied to bring the number strictly under 2. #Given an integer, return its iterated square root. Return "invalid" if it is negative. #Idea for iterated square root by Richard Spence. import math def i_sqrt(n): if n < 0: return 'invalid' count = 0 while n >= 2: n **= 0.5 count += 1 return count print(i_sqrt(1)) #➞ 0 print(i_sqrt(2)) #➞ 1 print(i_sqrt(7)) #➞ 2 print(i_sqrt(27)) #➞ 3 print(i_sqrt(256)) #➞ 4 print(i_sqrt(-1) ) #➞ "invalid"
edb6aaff5ead34484d01799aef3df830208b574c
ravalrupalj/BrainTeasers
/Edabit/Identical Characters.py
460
4.125
4
#Check if a String Contains only Identical Characters #Write a function that returns True if all characters in a string are identical and False otherwise. #Examples #is_identical("aaaaaa") ➞ True #is_identical("aabaaa") ➞ False #is_identical("ccccca") ➞ False #is_identical("kk") ➞ True def is_identical(s): return len(set(s))==1 print(is_identical("aaaaaa")) print(is_identical("aabaaa") ) print(is_identical("ccccca")) print(is_identical("kk"))
da002bf4a8ece0c60f4103e5cbc92f641d27f573
ravalrupalj/BrainTeasers
/Edabit/Stand_in_line.py
674
4.21875
4
#Write a function that takes a list and a number as arguments. Add the number to the end of the list, then remove the first element of the list. The function should then return the updated list. #For an empty list input, return: "No list has been selected" def next_in_line(lst, num): if len(lst)>0: t=lst.pop(0) r=lst.append(num) return lst else: return 'No list has been selected' print(next_in_line([5, 6, 7, 8, 9], 1)) #➞ [6, 7, 8, 9, 1] print(next_in_line([7, 6, 3, 23, 17], 10)) #➞ [6, 3, 23, 17, 10] print(next_in_line([1, 10, 20, 42 ], 6)) #➞ [10, 20, 42, 6] print(next_in_line([], 6)) #➞ "No list has been selected"
157488073da151c9907c967304ddd0f7933d22aa
ravalrupalj/BrainTeasers
/Edabit/Format_IV.py
813
3.53125
4
#Format IV: Escaping Curly Braces #For each challenge of this series you do not need to submit a function. Instead, you need to submit a template string that can formatted in order to get a certain outcome. #Write a template string according to the following example. Notice that the template will be formatted twice: #Example a = "John" b = "Joe" template = "My best friend is ." template.format(1).format(a, b) #➞ "My best friend is {{{}}}." #Tips #Curly braces can be escaped by doubling them. In a format string, {{ and }} are literal { and } respectively. #For example: "{} these, not these {{}}".format("Substitute") #➞ "Substitute these, not these {}" #Notes #Sumbit a string, not a function. #Do not change the name of the variable template. #You can find all the exercises in this series over here.
b5255591c5a67f15767deee268a1972ca61497cd
ravalrupalj/BrainTeasers
/Edabit/Emphasise_the_Words.py
617
4.21875
4
#Emphasise the Words #The challenge is to recreate the functionality of the title() method into a function called emphasise(). The title() method capitalises the first letter of every word. #You won't run into any issues when dealing with numbers in strings. #Please don't use the title() method directly :( def emphasise(string): r='' for i in string.split(): t=(i[0].upper())+(i[1:].lower())+' ' r=r+t return r.rstrip() print(emphasise("hello world")) #➞ "Hello World" print(emphasise("GOOD MORNING") ) #➞ "Good Morning" print(emphasise("99 red balloons!")) #➞ "99 Red Balloons!"
75e00bb80cdd283eabe3f5b5733308c08ebde710
ravalrupalj/BrainTeasers
/Edabit/Who_Oldest.py
426
4.09375
4
#Given a dictionary containing the names and ages of a group of people, return the name of the oldest person. #All ages will be different. def oldest(dict): a=max(dict[i] for i in dict) for k,v in dict.items(): if a==v: return k print(oldest({ "Emma": 71, "Jack": 45, "Amy": 15, "Ben": 29 }) ) #➞ "Emma" print(oldest({ "Max": 9, "Josh": 13, "Sam": 48, "Anne": 33 })) #➞ "Sam"
6eceebf49b976ec2b757eee0c7907f2845c65afd
ravalrupalj/BrainTeasers
/Edabit/Is_String_Order.py
405
4.25
4
#Is the String in Order? #Create a function that takes a string and returns True or False, depending on whether the characters are in order or not. #You don't have to handle empty strings. def is_in_order(txt): t=''.join(sorted(txt)) return t==txt print(is_in_order("abc")) #➞ True print(is_in_order("edabit")) #➞ False print(is_in_order("123")) #➞ True print(is_in_order("xyzz")) #➞ True
1e445c240e84fdc0cc391791be49014670fc031c
ravalrupalj/BrainTeasers
/Edabit/Numbered_Alphabet.py
525
3.875
4
#Numbered Alphabet #Create a function that converts a string of letters to their respective number in the alphabet. #Make sure the numbers are spaced. #A B C D E F G H I J K L M N O P Q R S T U V W ... #0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 ... def alph_num(txt): l='' for i in txt: t=ord(i)-65 l=l+' '+str(t) return l.strip() print(alph_num("XYZ") ) #➞ "23 24 25" print(alph_num("ABCDEF") ) #➞ "0 1 2 3 4 5" print(alph_num("JAVASCRIPT")) #➞ "9 0 21 0 18 2 8 15 10"
56bf743185fc87230c9cb8d0199232d393757809
ravalrupalj/BrainTeasers
/Edabit/Day 2.5.py
793
4.53125
5
#He tells you that if you multiply the height for the square of the radius and multiply the result for the mathematical constant π (Pi), you will obtain the total volume of the pizza. Implement a function that returns the volume of the pizza as a whole number, rounding it to the nearest integer (and rounding up for numbers with .5 as decimal part). #vol_pizza(1, 1) ➞ 3 # (radius² x height x π) = 3.14159... rounded to the nearest integer. #vol_pizza(7, 2) ➞ 308 #vol_pizza(10, 2.5) ➞ 785 import math def vol_pizza(radius, height): t=(radius ** 2) * height *math.pi y=round(t,1) return round(y) print(vol_pizza(1, 1)) # (radius² x height x π) = 3.14159... rounded to the nearest integer. print(vol_pizza(7, 2)) print(vol_pizza(10, 2.5)) print(vol_pizza(15, 1.3))
d9d1a7dbd41fea7d00f7299ae6708fc46e21d42d
ravalrupalj/BrainTeasers
/Edabit/Day 4.4.py
510
4.46875
4
#Is It a Triangle? #Create a function that takes three numbers as arguments and returns True if it's a triangle and False if not. #is_triangle(2, 3, 4) ➞ True #is_triangle(3, 4, 5) ➞ True #is_triangle(4, 3, 8) ➞ False #Notes #a, b and, c are the side lengths of the triangles. #Test input will always be three positive numbers. def is_triangle(a, b, c): return a+b>c and a+c>b and b+c>a print(is_triangle(2, 3, 4)) print(is_triangle(3, 4, 5)) print(is_triangle(4, 3, 8)) print(is_triangle(2, 9, 5))
a055bcd166678d801d9f2467347d9dfcd0e49254
ravalrupalj/BrainTeasers
/Edabit/Count_and_Identify.py
832
4.25
4
#Count and Identify Data Types #Given a function that accepts unlimited arguments, check and count how many data types are in those arguments. Finally return the total in a list. #List order is: #[int, str, bool, list, tuple, dictionary] def count_datatypes(*args): lst=[type(i) for i in args] return [lst.count(i) for i in (int, str, bool, list, tuple, dict)] print(count_datatypes(1, 45, "Hi", False) ) #➞ [2, 1, 1, 0, 0, 0] print(count_datatypes([10, 20], ("t", "Ok"), 2, 3, 1) ) #➞ [3, 0, 0, 1, 1, 0] print(count_datatypes("Hello", "Bye", True, True, False, {"1": "One", "2": "Two"}, [1, 3], {"Brayan": 18}, 25, 23) ) #➞ [2, 2, 3, 1, 0, 2] print(count_datatypes(4, 21, ("ES", "EN"), ("a", "b"), False, [1, 2, 3], [4, 5, 6]) ) #➞ [2, 0, 1, 2, 2, 0] #Notes #If no arguments are given, return [0, 0, 0, 0, 0, 0]
fde94a7ba52fa1663a992ac28467e42cda866a9b
ravalrupalj/BrainTeasers
/Edabit/Lexicorgraphically First_last.py
762
4.15625
4
#Lexicographically First and Last #Write a function that returns the lexicographically first and lexicographically last rearrangements of a string. Output the results in the following manner: #first_and_last(string) ➞ [first, last] #Lexicographically first: the permutation of the string that would appear first in the English dictionary (if the word existed). #Lexicographically last: the permutation of the string that would appear last in the English dictionary (if the word existed). def first_and_last(s): t=sorted(s) e=''.join(t) r=e[::-1] p=e,r return list(p) print(first_and_last("marmite")) #➞ ["aeimmrt", "trmmiea"] print(first_and_last("bench")) #➞ ["bcehn", "nhecb"] print(first_and_last("scoop")) #➞ ["coops", "spooc"]
5c503edd8d4241b5e674e0f88b5c0edbe0888235
ravalrupalj/BrainTeasers
/Edabit/Explosion_Intensity.py
1,312
4.3125
4
#Explosion Intensity #Given an number, return a string of the word "Boom", which varies in the following ways: #The string should include n number of "o"s, unless n is below 2 (in that case, return "boom"). #If n is evenly divisible by 2, add an exclamation mark to the end. #If n is evenly divisible by 5, return the string in ALL CAPS. #The example below should help clarify these instructions. def boom_intensity(n): if n<2: return 'boom' elif n%2==0 and n%5==0: return 'B'+'O'*n+'M'+'!' elif n%2==0: return 'B'+('o'*n)+'m'+'!' elif n%5==0: return 'B' + ('O' * n) + 'M' else: return 'B'+('o'*n)+'m' print(boom_intensity(4) ) #➞ "Boooom!" # There are 4 "o"s and 4 is divisible by 2 (exclamation mark included) print(boom_intensity(1) ) #➞ "boom" # 1 is lower than 2, so we return "boom" print(boom_intensity(5) ) #➞ "BOOOOOM" # There are 5 "o"s and 5 is divisible by 5 (all caps) print(boom_intensity(10) ) #➞ "BOOOOOOOOOOM!" # There are 10 "o"s and 10 is divisible by 2 and 5 (all caps and exclamation mark included) #Notes #A number which is evenly divisible by 2 and 5 will have both effects applied (see example #4). #"Boom" will always start with a capital "B", except when n is less than 2, then return a minature explosion as "boom".
bc123a73adc60347bc2e8195581e6d556b27c329
ravalrupalj/BrainTeasers
/Edabit/Check_if_an_array.py
869
4.28125
4
#Check if an array is sorted and rotated #Given a list of distinct integers, create a function that checks if the list is sorted and rotated clockwise. If so, return "YES"; otherwise return "NO". def check(lst): posi = sorted(lst) for i in range(0,len(lst)-1): first=posi.pop(0) posi.append(first) if posi==lst: return "YES" return 'NO' print(check([3, 4, 5, 1, 2])) #➞ "YES" # The above array is sorted and rotated. # Sorted array: [1, 2, 3, 4, 5]. # Rotating this sorted array clockwise # by 3 positions, we get: [3, 4, 5, 1, 2]. print(check([1, 2, 3])) #➞ "NO" # The above array is sorted but not rotated. print(check([7, 9, 11, 12, 5]) ) #➞ "YES" # The above array is sorted and rotated. # Sorted array: [5, 7, 9, 11, 12]. # Rotating this sorted array clockwise # by 4 positions, we get: [7, 9, 11, 12, 5].
a3b5f7ffe220bd211b6fde53c99b9bcb086dbf39
ravalrupalj/BrainTeasers
/Edabit/Reverse_the_odd.py
656
4.4375
4
#Reverse the Odd Length Words #Given a string, reverse all the words which have odd length. The even length words are not changed. def reverse_odd(string): new_lst=string.split() s='' for i in new_lst: if len(i)%2!=0: t=i[::-1] s=s+t+' ' else: s=s+i+' ' return s.strip() print(reverse_odd("Bananas")) #➞ "sananaB" print(reverse_odd("One two three four")) #➞ "enO owt eerht four" print(reverse_odd("Make sure uoy only esrever sdrow of ddo length")) #➞ "Make sure you only reverse words of odd length" #Notes #There is exactly one space between each word and no punctuation is used.
9e340932b584ffa288e7a3cf066e5c93ed2c8a1b
ravalrupalj/BrainTeasers
/OOP/Inheritance Class.py
504
3.9375
4
#Innheritance-Super class and Sub class #Single Level Inheritance #Multi Level Inheritance #Mulitple INheritance class A: def feature1(self): print('Feature 1 working') def feature2(self): print('Feature 2 working') class B(): def feature3(self): print('Feature 3 working') def feature4(self): print('Feature 4 working') class C(A,B): def feature5(self): print('Feature 5 working') a1=A() b1=B() a1.feature1() a1.feature2() c1=C() c1.feature1()