blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
c31acba735310ace1d4f99c7715f4017d034b2ba | slamatik/codewars | /6 kyu/Find the missing letter.py | 380 | 3.828125 | 4 | from string import ascii_letters
def find_missing_letter(chars):
let = ascii_letters
p = 0
while let[p] != chars[0]:
p += 1
for i in range(len(chars)):
if chars[i] == let[p]:
p += 1
else:
return let[p]
# return p, let[p]
st = ["a","b","c","d","f"]
# st = ["O", "Q", "R", "S"]
print(find_missing_letter(st))
|
ddb51a40e3cbc49e856f6a9f95cf9637f39c372f | slamatik/codewars | /6 kyu/Unique in Order 6 kyu.py | 350 | 3.8125 | 4 | def unique_in_order(iterable):
if len(iterable) == 0:
return []
table = [iterable[0]]
for i in range(1, len(iterable)):
if iterable[i] != table[-1]:
table.append(iterable[i])
return table
print(unique_in_order('AAAABBBCCDAABBB'))
print(unique_in_order('ABBCcAD'))
print(unique_in_order([1, 2, 2, 3, 3]))
|
aea0c94a63607d53c219cdcff663fd3456c2cdf8 | slamatik/codewars | /5 kyu/Compute the Largest Sum of all Contiguous Subsequences 5 kyu.py | 281 | 3.765625 | 4 | def largest_sum(arr):
if len(arr) == 0:
return 0
cache = [arr[0]]
for i in range(1, len(arr)):
cache.append(max(arr[i], cache[-1] + arr[i]))
return 0 if max(cache) < 0 else max(cache)
data = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print(largest_sum(data)) |
adfb408d885e848cd1551331d8d6ba2ea3dfa10a | fanchunguang/python | /com/alrti/binary-search.py | 5,934 | 4.09375 | 4 | # !/usr/bin/env python
# !-*-coding:utf-8 -*-
# !@Author : fanchg
# !@Time : 2019/3/14
import unittest
class Solution:
def searchInsert(self, nums, target) -> int:
"""
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引
:param nums:
:param target:
:return:
"""
start, mid, end = 0, 0, len(nums)-1
while start <= end:
mid = (start + end) // 2
if target < nums[mid]:
end = mid - 1
elif target > nums[mid]:
start = mid + 1
else:
return mid
return start
def search(self, nums, target: int) -> int:
"""假设按照升序排序的数组在预先未知的某个点上进行了旋转,
搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1
"""
if not nums:
return -1
start, end = 0, len(nums)-1
while start <= end:
mid = (start + end)//2
if target == nums[mid]:
return mid
elif target < nums[mid]:
if nums[start] < nums[mid]:
if target >= nums[start]:
end = mid - 1
else:
start = mid + 1
elif nums[start] > nums[mid]:
end = mid - 1
else:
start = mid + 1
elif target > nums[mid]:
if nums[start] < nums[mid]:
start = mid+1
elif nums[start] > nums[mid]:
if nums[start] < target:
end = mid - 1
else:
start = mid + 1
else:
end = mid + 1
return -1
def searchRange(self, nums, target):
"""
给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置
:param nums:
:param target:
:return:
"""
start, mid, end = 0, 0, len(nums)-1
adr = [-1, -1]
while start < end:
mid = (start + end) // 2
if target > nums[mid]:
start = mid + 1
elif target < nums[mid]:
end = mid - 1
else:
if target > nums[mid-1] or mid==0:
adr[0] = mid
elif target < nums[mid+1] or mid == len(nums)-1:
adr[1] = mid
return adr
def binary_search(self, nums, target, right=False):
lo, hi = 0, len(nums)
while lo < hi:
# print("Trying to find %d at [%d, %d]" % (target, lo, hi))
mid = (lo + hi) // 2
# print("Comparing target %d with mid %d[#%d]" % (target, nums[mid], mid))
if target > nums[mid] or (right and target == nums[mid]):
lo = mid + 1
else:
hi = mid
return lo
# def searchRange(self, nums, target):
# """
# :type nums: List[int]
# :type target: int
# :rtype: List[int]
# """
# left = self.binary_search(nums, target)
# if left == len(nums) or nums[left] != target:
# return [-1, -1]
# right = self.binary_search(nums, target, True) - 1
# return [left, right]
def countSmaller(self, nums):
"""
给定一个整数数组 nums,按要求返回一个新数组 counts。数组 counts 有该性质: counts[i] 的值是 nums[i] 右侧小于 nums[i] 的元素的数量
:param nums:
:return:
"""
dictnary = {}
j = 0
temp = nums.copy()
lis = sorted(temp)
for i in range(0, len(lis)):
j += 1
dictnary[str(lis[i])] = j
counts = [0 for i in range(0, len(nums))]
c = bitArray(len(nums))
for i in range(len(nums) - 1, -1, -1):
n = dictnary[str(nums[i])]
counts[i] = c.get(n - 1)
c.add(n, 1)
return counts
def mergekLists(self, lists):
if not lists:
return None
res = []
for a in lists:
while a:
res.append(a.val)
a = a.next
res.sort()
p = ListNode(0)
q = p
for i in range(0, len(res)):
q.next = ListNode(res[i])
q = q.next
return p.next
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class bitArray:
def __init__(self, n):
self.list = [0 for i in range(0, n+1)]
self.n = n
def add(self, x, num):
while x < self.n:
self.list[x] += num
x += (x & (-x))
def get(self, x):
ans = 0
while x > 0:
ans += self.list[x]
x -= (x & (-x))
return ans
class TestBinarySearch(unittest.TestCase):
def testSearch(self):
target = 0
nums = [4,5,6,7,0,1,2]
result = Solution.searchRange(self, nums, target)
print('%s :' + str(result))
def testSearchRange(self):
target = 0
nums = [4,5,6,7,0,1,2]
result = Solution.search(self, nums, target)
print('%s :' + str(result))
def testCountSmaller(self):
nums = [5, 2, 6, 1]
result = Solution.countSmaller(self, nums)
print('%s :' + str(result))
def testMerge(self):
list = [[1, 4, 5], [1, 3, 4], [2, 6]]
result= Solution.mergekLists(self, list)
print('%s :' + str(result))
if __name__ == '__main__':
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestBinarySearch.testCountSmaller()))
unittest.TextTestRunner().run(suite)
|
fc7ace8156f62d5b0388b7ad7052dfd64fa0e755 | ksu-is/Hangman_with_GUI_and_Difficulties | /testing.py | 6,853 | 3.71875 | 4 | from tkinter import *
import random
from tkinter import messagebox
from ISProject.Hangman_with_GUI_and_Difficulties.EasyWords import easy_list
from ISProject.Hangman_with_GUI_and_Difficulties.NormalWords import normal_list
from ISProject.Hangman_with_GUI_and_Difficulties.HardWords import hard_list
def get_difficulty_word(): # pick's the difficultly
while True:
mode_ui = input('What Difficulty Would You Like To Play?\n(E)asy, (N)ormal {recommended}, or (H)ard: ')
# put function in each statement below so the correct difficulty gets put on word variable
if mode_ui.lower() == 'e': # play easy use another function if needed
random_word = random.choice(easy_list)
return random_word.upper()
elif mode_ui.lower() == 'n': # play normal
random_word = random.choice(normal_list)
return random_word.upper()
elif mode_ui.lower() == 'h': # play hard
random_word = random.choice(hard_list)
return random_word.upper()
else:
print('Invalid input, try again.')
list_word = []
file1 = get_difficulty_word()
# Appending words from file to the list
for x in file1:
list_word.append(x.replace('\n', ''))
print(list_word)
# word = random.choice(mywords)
the_word = list(list_word)
p = []
s = '_ ' * len(the_word)
p = s.split(' ')
p.pop(len(the_word))
actual = the_word.copy()
class Hangman: # tkinter
def __init__(self, master):
self.count = 0
self.structure(master)
self.rr = master
def structure(self, master):
""" Instruction Label """
# Create instruction label for Program
self.inst_lbl = Label(master, text="Welcome to Hangman Game!")
self.inst_lbl.grid(row=0, column=0, columnspan=2, sticky=W)
""" Guess Input """
# Create label for entering Guess
self.guess_lbl = Label(master, text="Enter your Guess:")
self.guess_lbl.grid(row=1, column=0, sticky=W)
# Create entry widget to accept Guess
self.guess_ent = Entry(master)
self.guess_ent.grid(row=1, column=1, sticky=W)
# Create a space
self.gap2_lbl1 = Label(master, text=" ")
self.gap2_lbl1.grid(row=2, column=0, sticky=W)
# Creating a submit button
self.submit_bttn = Button(master, text="Submit", command=self.submit, height=1, width=20)
self.submit_bttn.grid(row=3, column=1, sticky=W)
master.bind('<Return>', self.submit)
# Create a space
self.gap2_lbl2 = Label(master, text=" ")
self.gap2_lbl2.grid(row=4, column=0, sticky=W)
""" RESET """ # DOESNT WORK
# Creating a reset button
self.reset_bttn = Button(master, text="Reset", command=self.reset, height=2, width=20)
self.reset_bttn.grid(row=9, column=2, sticky=W)
# Create a space
self.gap2_lbl3 = Label(master, text=" ")
self.gap2_lbl3.grid(row=5, column=0, sticky=W)
self.inst_lb2 = Label(master, text='Life:10')
self.inst_lb2.grid(row=1, column=2, columnspan=2, sticky=W)
# Creating Label to Display Message
self.inst_lb3 = Label(master, text='')
self.inst_lb3.grid(row=6, column=0, columnspan=2, sticky=W)
# Creating label to display current Guessed Status of Word
self.curr_char1 = Label(master, text=p)
self.curr_char1.place(x=100, y=130)
self.curr_char = Label(master, text="Current Status:")
self.curr_char.place(x=0, y=130)
# Create a Hangman's Background
self.c = Canvas(master, height=300, width=200)
self.c.grid(row=9, column=0, sticky=W)
self.l = self.c.create_line(70, 20, 70, 250, width=2)
self.l1 = self.c.create_line(70, 20, 150, 20, width=2)
self.l2 = self.c.create_line(150, 20, 150, 50, width=2)
def current_status(self, char):
self.curr_char1 = Label(self.rr, text=char)
self.curr_char1.place(x=100, y=130)
def reset(self): # DOESNT WORK
self.guess_ent.delete(0, 'end')
def submit(self, *args):
# Taking Entry From Entry Field
char = self.guess_ent.get()
# Checking whether Entry Field is empty or not
if (len(char) == 0):
messagebox.showwarning("Warning", "Entry field is Empty")
if (len(char) > 1):
messagebox.showwarning("Warning", "Enter the single letter")
if char in actual and len(char) == 1:
l = actual.count(char)
for j in range(l):
i = actual.index(char)
p.insert(i, char)
p.pop(i + 1)
actual.insert(i, '_')
actual.pop(i + 1)
self.inst_lb2.config(text='Life:' + str(10 - self.count))
self.inst_lb3.config(text='Right Guessed!')
self.guess_ent.delete(0, 'end')
self.current_status(p)
elif (len(char) == 1):
self.count = self.count + 1
self.inst_lb2.config(text='Life:' + str(10 - self.count))
self.inst_lb3.config(text='Wrong Guessed!')
self.guess_ent.delete(0, 'end')
# Creating Hangman's parts orderwise if wrong character is Guessed
if (self.count == 1):
self.cir = self.c.create_oval(125, 100, 175, 50, width=2)
elif (self.count == 2):
self.el = self.c.create_line(135, 65, 145, 65, width=2)
elif (self.count == 3):
self.er = self.c.create_line(155, 65, 165, 65, width=2)
elif (self.count == 4):
self.no = self.c.create_line(150, 70, 150, 85, width=2)
elif (self.count == 5):
self.mo = self.c.create_line(140, 90, 160, 90, width=2)
elif (self.count == 6):
self.l3 = self.c.create_line(150, 100, 150, 200, width=2)
elif (self.count == 7):
self.hl = self.c.create_line(150, 125, 100, 150, width=2)
elif (self.count == 8):
self.hr = self.c.create_line(150, 125, 200, 150, width=2)
elif (self.count == 9):
self.fl = self.c.create_line(150, 200, 100, 225, width=2)
elif (self.count == 10):
self.fr = self.c.create_line(150, 200, 200, 225, width=2)
# Condition of Player Won
if (p == the_word):
self.inst_lb3.config(text='You guessed the word!')
messagebox.showinfo("Hello", "You Won")
self.rr.destroy()
# Condition Of player Loose
elif (self.count >= 10):
self.inst_lb3.config(text='You lost.... the word is ' + get_difficulty_word())
messagebox.showinfo("Hello", "You lost please try again!")
self.rr.destroy()
root = Tk()
root.title("Hangman Game")
root.geometry("580x480")
app = Hangman(root)
root.mainloop()
|
c3debb20ebe291fd2a4efda4c01951f64bd91817 | gany-c/DataStructures | /src/misc/MukanoolNerkaanal.py | 2,771 | 3.96875 | 4 | """
--------------------------------
Given 2 integers represented as 2 arrays of single digit integers,
add them together and output the result in the form of array of single digit integers.
For example:
Input: [3, 4, 5] and [9, 4] (represent 345 and 94)
Output: [4, 3, 9] (represents 439)
--------------------------------
"""
def add_integer_array(array_1: int[], array_2: int[]): int[]
if !array_1 or !array_2:
return
output = []
# 3rd param is for carry over
# 4th param is for index from end
# 5th param is the output
traverse(array_1, array_2, 0, 0, output)
return output
def traverse(array_1, array_2, carry_over, index, output)
pos_1 = len(array_1 - 1) - index
pos_2 = len(array_2 - 1) - index
# handle -ve pos here
first_digit = 0
second_digit = 0
if pos_1 >= 0:
first_digit = array_1[pos_1]
if pos_2 >=0:
second_digit = array_2[pos_2]
local_sum = first_digit + second_digit + carry_over
digit = local_sum % 10
new_carry = local_sum / 10
output_pos = len(output -1) - index
output[output_pos] = digit
if (pos_1 < 0) && (pos_2 < 0) :
return
else:
traverse(array_1, array_2, new_carry, index + 1, output)
"""
Given an input string where all spaces have been removed, and an English dictionary, insert spaces back into the string so that it contains all valid words.
Example:
1.Input: s = "cathat", wordDict = ["cat","hat"] Output: "cat hat"
2.Input: s = "applepenapple", wordDict = ["apple","pen"] Output: "apple pen apple"
3.Input: s = "catshat", wordDict = ["cat","hat"] Output: ""
4.Input: s = "catha", wordDict = ["cat","hat"] Output: ""
5.Input: s = "pencathat", wordDict = ["cat","hat"] Output: ""
6.Input: s = "pencathat", wordDict = ["cat","hat", "pen"] Output: "pen cat hat"
7.Input: s = "caterhat", wordDict = ["cat", "cater","hat"] Output: "cater hat"
8.Input: s = "caterhat", wordDict = ["cat", "cater","hat", "er"] Output: ["cater hat"], ["cat er hat"]
"""
def insert_spaces(sentence: str, wordDict: str[], OUtput = ""): output:str
if (sentence == len 0):
return
match_words = []
for word in wordDict:
if starts_with(sentence, word):
match_words.append(append)
if len(match_words) == 0:
return ""
else:
for match_word in match_words:
new_sent = remove_first(
#try if a solution emerges in any of the matchwords recursively
insert_spaces(new_sent, wordDict, match_word
|
4b798d3491f597c4dec773b780243dace11b5958 | gany-c/DataStructures | /src/string/redditDictionary.py | 2,449 | 4.09375 | 4 | # import requests
# import mysql.connector
# import pandas as pd
# At Reddit, a big part of our job is to let our users find the best stuff in Reddit. To do this, we use a Search Engine, which lets us find Posts that match a query given by a user. For example, if you search for "meme", we want to be able to show all of the posts that use the word meme in their title of explanatory text. For this interview, we want you to build the simplest system that can do that job: Given a query, find all of the "documents" that contain the word or words in that query. We're going to start really simple, and will just match single words.
# We really are looking for the simplest approach to start with, so don't overthink the first pass code
# Having said that, we want to be able to add more sentences to the index, without re-indexing the sentences we've already added
# The sample sentences are:
def preprocess(sentences):
# key = word, value = list of sentences
output = {}
for sentence in sentences:
words = sentence.split()
for word in words:
if word in output.keys():
sent_set = output[word]
sent_set.add(sentence)
output[word] = sent_set
else:
sent_set = {sentence, }
output[word] = sent_set
return output
def findSentencesMapBased(query, sentence_map):
if query in sentence_map.keys():
return sentence_map[query]
else:
return set()
def findSentences(query, sentences):
output = []
for sentence in sentences:
# creates a list of words
words = sentence.split()
# linear lookup inside a list
if query in words:
output.append(sentence)
return output
sentences = [
'the quick brown fox',
'the slow brown cow',
'to be or not to be that is the question',
]
# The queries are:
queries = [
'the',
'cow',
'to',
]
print(findSentences('cow', sentences))
print(findSentences('ow', sentences))
print(findSentences('the', sentences))
print(findSentences('he', sentences))
print("========================================")
sentences_map = preprocess(sentences)
print(findSentencesMapBased('cow', sentences_map))
print(findSentencesMapBased('ow', sentences_map))
print(findSentencesMapBased('the', sentences_map))
print(findSentencesMapBased('he', sentences_map))
|
e465bf117aef5494bb2299f3f2aaa905fb619b52 | purple-phoenix/dailyprogrammer | /python_files/project_239_game_of_threes/game_of_threes.py | 1,346 | 4.25 | 4 | ##
# Do not name variables "input" as input is an existing variable in python:
# https://stackoverflow.com/questions/20670732/is-input-a-keyword-in-python
#
# By convention, internal functions should start with an underscore.
# https://stackoverflow.com/questions/11483366/protected-method-in-python
##
##
# @param operand: number to operate on.
# @return boolean: If inputs are valid.
##
def game_of_threes(operand: int) -> bool:
# Check for invalid inputs first
if operand < 1:
print("Invalid input. Starting number must be greater than zero")
return False
if operand == 1:
print(operand)
return True
# As prior functional blocks all return, there is no need for "elif" control blocks
if _divisible_by_three(operand):
print(str(operand) + " 0")
return game_of_threes(int(operand / 3))
if _add_one_divisible_by_three(operand):
print(str(operand) + " 1")
return game_of_threes(operand + 1)
if _sub_one_divisible_by_three(operand):
print(str(operand) + " -1")
return game_of_threes(operand - 1)
def _divisible_by_three(num: int) -> bool:
return num % 3 == 0
def _add_one_divisible_by_three(num: int) -> bool:
return (num + 1) % 3 == 0
def _sub_one_divisible_by_three(num: int) -> bool:
return (num - 1) % 3 == 0
|
fd29d21e8715829139f3b4ef11116c8cb85b8c69 | saotian/p1804 | /eryueyizhou/duotai.py | 312 | 3.59375 | 4 | class Duck(object):
def walk(self):
print("鸭子在走路")
def swim(self):
print("鸭子在游泳")
class People(object):
def walk(self):
print("老王在走路")
def swim(self):
print("老王在游泳")
def Func(obj):
obj.walk()
obj.swim()
duck = Duck()
ren = People()
Func(duck)
Func(ren)
|
5edc02fadd4b7bc1c910a97c0a5a9e2e3eacec09 | saotian/p1804 | /lei/people.py | 318 | 3.59375 | 4 | class PeopleYt(object):
def __init__(self):
self.__money = 0
def getmoney(self):
return self.__money
def setmoney(self,value):
self.__money = value
a = property(getmoney,setmoney)
class zhangsan(PeopleYt):
def __init__(self):
PeopleYt.__init__(self)
zs=zhangsan()
print(zs.a)
zs.a = 1000
print(zs.a)
|
a667dadc01bcbce1451bfaa6e1565ecf83116649 | saotian/p1804 | /eryueyizhou/xiaoming.py | 308 | 3.640625 | 4 | class People(object):
guoji = "china"
def __init__(eslf):
self.name = "小明"
def get_name(self):
return self.name
@classmethod
def get_guoji(cls):
return cls.guoji
def say_chinese(self):
print("中国话")
xiaoming = People()
print(People.guoji)
print(People.get-guoji)
People.say_chinese()
|
11d697fdccf31230f1a8fae44a79e59f330863d1 | saotian/p1804 | /05/6_ren人类.py | 344 | 3.828125 | 4 | class People(object):
def __init__(self,name,height,weight):
self.name = name
self.height = height
self.weight = weight
def introduce(self):
print("我的名字是%s,身高%s,体重%s"%(self.name,self.height,self.weight))
huahua = People("花花",180,130)
huahua.introduce()
caocao = People("草草",185,120)
caocao.introduce()
|
1a79515ce732ef169510986cbf42af807a06650d | JonTurner-Janrain/general_work | /record-generator/lib/random_date.py | 810 | 4.03125 | 4 | """return a date(time) string for the given the date-time format"""
import time
from random import randint
def random_date(date_format):
""" Return a random(ish) date for use as birthdays and the like. """
string = "{}-{}-{} {}:{}:{}".format(randint(1950, 2000),
str(randint(1, 12)).zfill(2),
# there's 28 days in every month, right?
str(randint(1,28)).zfill(2),
str(randint(0,23)).zfill(2),
str(randint(0,59)).zfill(2),
str(randint(0,59)).zfill(2))
parsed_time = time.strptime(string, "%Y-%m-%d %H:%M:%S")
return time.strftime(date_format, parsed_time) |
e8fa9fd7604523316bee7e9ba557dccbacb479de | robertocrw/python | /myCal.py | 2,548 | 3.953125 | 4 | '''Este codigo esta dividido em 4 fases'''
# 1.0 Definir as funções
# 2.0 Chamar os botões
# 3.0 Declarar as entradas
# 4.0 Declara as variaveis primeiron e segundon
# 4.1 Importar, declara o tk(), e finalizar o mainloop(), e definir as dimensões.
#4.1
from tkinter import * # importando as definiçoes tk
#4.1
myCal = Tk() #começo da app
#1.0
def somar(): # função do botão1
somar1 = float(primeiron.get()) # primeiron faz referencia a primeira entrada
somar2 = float(segundon.get()) # primeiron faz referencia a segunda entrada
somar3 = somar1 + somar2
labelresult = Label(myCal,text='%.2f' %(somar3)).grid(row=9, column=0)
def dividir(): # função do botão2
dividir1 = float(primeiron.get())
dividir2 = float(segundon.get())
dividir3 = dividir1 / dividir2
labelresult = Label(myCal,text='%.2f' %(dividir3)).grid(row=9, column=0)
def multiplicar(): # função do botão3
multiplicar1 = float(primeiron.get())
multiplicar2 = float(segundon.get())
multiplicar3 = multiplicar1 * multiplicar2
labelresult = Label(myCal,text='%.2f' %(multiplicar3)).grid(row=9, column=0)
def fatorar(): # função do botão4
fatorar1 = float(primeiron.get())
fatorar2 = float(segundon.get())
fatorar3 = fatorar1**fatorar2
labelresul = Label(myCal,text='%.2f' %(fatorar3)).grid(row=9, column=0)
def percentagem(): # função do botão5
percentagem1 = float(primeiron.get())
percentagem2 = float(segundon.get())
percentagem3 = percentagem1 % percentagem2
labelresult = Label(myCal,text='%.2f' %(percentagem3)).grid(row=9, column=0)
#4.1
myCal.geometry('100x250+300+300') # dimensao da app
myCal.title('myCal_1.0') # titulo da app
#2.0
botao1 = Button(myCal,text='Somar', command=somar).grid(row=1, column=0) # botões
botao2 = Button(myCal,text='Dividir', command=dividir).grid(row=2, column=0)
botao3 = Button(myCal,text='Multiplicar', command=multiplicar).grid(row=3, column=0)
botao4 = Button(myCal,text='Fatorar', command=fatorar).grid(row=4, column=0)
botao5 = Button(myCal,text='Percentagem', command=percentagem).grid(row=5, column=0)
#4.1
primeiron = StringVar() #difinisão da variavel primeiron
segundon = StringVar() #definição da variavel segundon
#3.0
entrada1 = Entry(myCal,textvariable=primeiron).grid(row=6, column=0) # comando de entrada
entrada2 = Entry(myCal,textvariable=segundon).grid(row=7, column=0) # comando de entrada
#botao = Button(myCal,text='Calcular' command=calculadora).grid(row=8, column=0)
#4.1
myCal.mainloop() # fechamento da app
|
cc58151fb96f524c85a647baf99c4bb2c3c7f09e | sheetla971/pycharm_newproject | /ter.py | 129 | 3.953125 | 4 | def check(a,b):
return a if a>b else b
a=input("first number:")
b=input("second number:")
a,b=int(a),int(b)
print(check(a,b)) |
0e12ca2f26cf00c1dd5a7be5e56c97903a3f29c5 | irenenikk/sentiment-analysis-comparison | /code/science_utils.py | 3,712 | 3.5 | 4 | from scipy.stats import binom
import numpy as np
import math
def calculate_p_value(N, k, q):
""" Calculates p-value using the binomial distribution. """
res = 0
for i in range(k+1):
res += binom.pmf(i, N, q)
return 2*res
def sign_test_p_value(plus, minus, null):
""" Calculates p-value for a two-tailed sign-test. """
N = plus+minus
k = min(plus, minus)
return calculate_p_value(N, k, 0.5)
def sign_test_lists(listA, listB):
""" A list-based sign test. """
assert len(listA) == len(listB), 'The lists should have the same amount of data points.'
plus, minus, null = 0, 0, 0
for i in range(len(listA)):
a = listA[i]
b = listB[i]
if a == b:
null += 1
elif a > b:
plus += 1
else:
minus += 1
return sign_test_p_value(plus, minus, null)
def sign_test_systems(test_data, system_A, system_B):
""" Returns the p-value of a two-tailed sign-test comparing two prediction systems."""
plus, minus, null = 0, 0, 0
for i in range(len(test_data)):
inp = test_data['review'].iloc[i]
a = system_A.predict(inp)
b = system_B.predict(inp)
true_label = test_data['sentiment'].iloc[i]
if a == b:
null += 1
elif true_label == a:
plus += 1
elif true_label == b:
minus += 1
return sign_test_p_value(plus, minus, null)
def get_accuracy(preds, Y):
return (preds == Y).sum()/len(preds)
def swap_randomly(A, B, shift_indx=None):
assert len(A) == len(B), 'Both lists have to be the same size.'
if shift_indx is None:
# sample random amount of indexes to swap using a coin toss
shift_amount = np.random.binomial(len(A), 0.5)
indexes = list(range(len(A)))
# flip the values in lists in random places
index_perm = np.random.permutation(indexes)
shift_indx = index_perm[:shift_amount]
tmp = A[shift_indx]
A[shift_indx] = B[shift_indx]
B[shift_indx] = tmp
return A, B
def permutation_test(true_labels, results_A, results_B, R=5000):
""" Monte carlo permutation test on two different prediction lists. """
acc_differences = np.zeros(R)
true_acc_A = get_accuracy(results_A, true_labels)
true_acc_B = get_accuracy(results_B, true_labels)
true_diff = np.abs(true_acc_A - true_acc_B)
for i in range(R):
shuff_A, shuff_B = swap_randomly(results_A, results_B)
acc_A = (shuff_A == true_labels).sum()/len(shuff_A)
acc_B = (shuff_B == true_labels).sum()/len(shuff_B)
acc_differences[i] = np.abs(acc_A - acc_B)
return ((acc_differences >= true_diff).sum()+1)/(R+1)
def sample_variance(data):
""" Calculate sample variance from data. """
mean = np.mean(data)
return np.sum(np.square(data-mean))
def get_mask(length, indexes):
""" Turn indices into a boolean mask. """
mask = np.zeros(length, dtype=bool)
mask[indexes] = True
return mask
def train_test_split_indexes(data, train_frac):
""" Returns a random index split into two. """
data_len = data.shape[0]
indexes = list(range(data_len))
rand_perm = np.random.permutation(indexes)
train_batch = math.floor(data_len*train_frac)
return rand_perm[:train_batch], rand_perm[train_batch:]
def get_train_test_split(train_frac, X, Y=None):
""" Returns a random split of data into two. If Y is given, it is assumed to be labels for X. """
train_indexes, test_indexes = train_test_split_indexes(X, train_frac)
if Y is None:
return X.iloc[train_indexes], X.iloc[test_indexes]
return X[train_indexes], Y[train_indexes], X[test_indexes], Y[test_indexes]
|
a897856eb5eb0b3b1786b20697825f2fd517f5e8 | ArtBelgorod/book | /city_functions.py | 245 | 3.578125 | 4 | def get_city_country(city,country,population = ""):
if population !="":
full_name = f"{city.title()},{country.title()} - population {population}!"
else:
full_name = f"{city.title()},{country.title()}"
return full_name |
18339a74d160d992d0e67c80e096dd00b247a40e | ArtBelgorod/book | /10_11_2.py | 401 | 3.65625 | 4 | import json
filename = "num.json"
try:
with open (filename) as f:
num = json.load(f)
except FileNotFoundError:
num = int(input("Введите Ваше любимое число - "))
filename = "num.json"
with open(filename, 'w') as f:
json.dump(num, f)
print("Мы Вас запомнили!")
else:
print(f"Ваше любимое число - {num}")
|
40ea12e7a031f2ad3330a4b9947acb718de6d4bd | duyhieuvo/human-detection-and-tracking-using-Optical-Flow | /PC/GUI.py | 1,657 | 3.515625 | 4 | import tkFileDialog as filedialog
from Tkinter import *
from Display import *
import os
def browse_button():
# Allow user to select a directory and store it in global variable folder_path
global folder_path
filename = filedialog.askdirectory()
folder_path.set(filename)
#List all files in the folder
files = os.listdir(filename)
print files
name = ""
#Loop through all files in the folder
for i,file in enumerate(files):
print file
#Find the "Trajectory" file
if "Trajectory" in file:
trajectory = i
print trajectory
#Find the "Time" file
elif "Time" in file:
time = i
print time
#Find the background image for displaying the result
elif "Captured" in file:
background = i
print background
#Find file with the result of human recognition if available
elif file.endswith(".txt"):
name = os.path.splitext(file)[0]
print name
print files[background]
if name!="":
showing = Display(filename + "/" + files[background],filename + "/" + files[trajectory],filename + "/" + files[time],name)
else:
showing = Display(filename + "/" + files[background],filename + "/" + files[trajectory],filename + "/" + files[time])
showing.showing()
print(filename)
root = Tk()
folder_path = StringVar()
lbl1 = Label(master=root,textvariable=folder_path)
lbl1.grid(row=0, column=1)
button2 = Button(text="Browse", command=browse_button)
button2.grid(row=0, column=3)
mainloop() |
17255846c2d4f9c4e1a9a96040989ddbc8f06118 | yb170442627/YangBo | /Python_ex/ex5_1.py | 1,109 | 3.78125 | 4 | # -*- coding: utf-8 -*-
name = 'YangBo'
age = 35 # not a lie
height = 74 # inches : 英寸
weight = 180 # lbs (pounds) 磅
eyes = 'Bule'
teeth = 'White'
hair = 'Brown'
#%s,表示格化式一个对象为字符, 把 name代表的字符串放到%s的位置中
print "Let's talk about %s." % name
#%d,整数. 把 height 代表的整数放到 %d 的位置中
print "He's %d inches tall." % height
print "He's %d pounds heavy." % weight
print "Actually that's not too heavy."
#%r : 不管什么都打印出来 , 所以这边的打印出来的name是 ‘YangBo’
print " %r He's got %s eyes and %s hair" % (name,eyes,hair)
print "His teeth are usually %s depending on the coffee." % teeth
#this line is tricky, try to get it exactly right
print "If I add %d , %d and %d I get %d." %(
age, height, weight, age + height + weight)
'''
The output is as follows:
Let's talk about YangBo.
He's 74 inches tall.
He's 180 pounds heavy.
Actually that's not too heavy.
'YangBo' He's got Bule eyes and Brown hair
His teeth are usually White depending on the coffee.
If I add 35 , 74 and 180 I get 289.
''' |
40dcaf6d0f51e671ed643d3c49d2071ed65df207 | yb170442627/YangBo | /Python_ex/ex25_1.py | 339 | 4.34375 | 4 | # -*- coding: utf-8 -*-
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
words = "where are you come from?"
word = break_words(words)
print word
word1 = sort_words(word)
print word1
|
a5341d137334ccca3977d0c4b85f17feeeaca78c | yb170442627/YangBo | /Python_ex/ex39.py | 457 | 4.125 | 4 | # -*- coding: utf-8 -*-
cities = {'SH': 'ShangHai', 'BJ': 'BeiJing','GZ': 'GanZhou'}
cities['GD'] = 'GuangDong'
cities['SD'] = 'ShanDong'
def find_city(themap, state):
if state in themap:
return themap[state]
else:
return "Not Found."
cities['_find'] = find_city
while True:
print "State?(ENTER to quit)",
state = raw_input("> ")
if not state: break
city_found = cities['_find'](cities,state)
print city_found |
448f476ddbd8ec3582c3913c8926f3181dfb8cf7 | yb170442627/YangBo | /Python_ex/ex33_1.py | 831 | 4.1875 | 4 | # -*- coding: utf-8 -*-
def append_num(num): # 定义了一个append_num(num)函数
i = 0 # 声明了一个常量 i
numbers = [] # 声明了一个空的列表 numbers = []
while i < num: # 执行while循环
print "At the top i is %d" % i
numbers.append(i) #调用列表的append方法,当i< num成立的时候,把i的值追加到numbers这个空的列表中
i = i + 1 # i + 1
return numbers # 返回 numbers 的值。给谁呢?给下面list这个变量。
#为什么?因为list这个变量调用了append_num(num)函数.
# 它把 6 这个参数传递给了append_num(num)函数,函数最终返回结果给list这个变量
list = append_num(6)
print list
#Python 词汇return 来将变量设置为“一个函数的值” |
31f0676f560bd845dc7ba12d65687ac682d08e4a | KaPiech/Various-programs-Python | /Kalkulator.py | 2,221 | 3.515625 | 4 | #Zadanie Kalkulator
import math
class Complex:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
def show_complex(self):
print("Wynik = ", self.r, " + ", self.i, "i")
def conjugate(self):
self.i = -self.i
def module(self):
return math.sqrt((self.r * self.r) + (self.i * self.i))
def add(self, y):
return Complex(self.r + y.r, self.i + y.i)
def subtract(self, y):
return Complex(self.r - y.r, self.i - y.i)
def multiplicate(self, y):
return Complex(((self.r * y.r) - (self.i - y.i)), ((self.r * y.i) + (self.i * y.r)))
while(1):
print("_________Kalkulator liczb zespolonych_________")
print("| 1.Dodawanie")
print("| 2.Odjmowanie")
print("| 3.Mnożenie")
print("| 4.Sprzężenie")
print("| 5.Moduł")
print("| 6.Zakończ")
n = int(input("Wybierz działanie: "))
if(n == 1):
r, i = input('Podaj część rzeczywistą i urojoną pierwszej liczby, oddzielone spacją: ').split()
z1 = Complex(float(r), float(i))
r, i = input('Podaj część rzeczywistą i urojoną drugiej liczby, oddzielone spacją: ').split()
z2 = Complex(float(r), float(i))
z3 = z1.add(z2)
z3.show_complex()
elif(n == 2):
r, i = input('Podaj część rzeczywistą i urojoną liczby, oddzielone spacją: ').split()
z1 = Complex(float(r), float(i))
r, i = input('Podaj część rzeczywistą i urojoną drugiej liczby, oddzielone spacją: ').split()
z2 = Complex(float(r), float(i))
z3 = z1.subtract(z2)
z3.show_complex()
elif(n == 3):
r, i = input('Podaj część rzeczywistą i urojoną pierwszej liczby, oddzielone spacją: ').split()
z1 = Complex(float(r), float(i))
r, i = input('Podaj część rzeczywistą i urojoną drugiej liczby, oddzielone spacją: ').split()
z2 = Complex(float(r), float(i))
z3 = z1.multiplicate(z2)
z3.show_complex()
elif(n == 4):
r, i = input('Podaj część rzeczywistą i urojoną pierwszej liczby, oddzielone spacją: ').split()
z1 = Complex(float(r), float(i))
z1.conjugate()
z1.show_complex()
elif(n == 5):
r, i = input('Podaj część rzeczywistą i urojoną pierwszej liczby, oddzielone spacją: ').split()
z1 = Complex(float(r), float(i))
print("Wynik = ", z1.module())
elif(n == 6):
break |
ea1c75a52acd753cc978ed712c92e17b78f7085f | KaPiech/Various-programs-Python | /Pięciu_filozofów_deadlock.py | 2,485 | 3.59375 | 4 | #Zadanie Pięciu filozofów wersja z deadlockiem(kelner)
import time
import sys
import threading
class Fork(object):
def __init__(self, num):
self.number = num
self.user = -1
self.lock = threading.Condition(threading.Lock())
self.taken = False
def drop_fork(self, user):
with self.lock:
while self.taken == False:
self.lock.wait()
self.user = -1
self.taken = False
sys.stdout.write("Filozof[ %s ] odłożył widelec[ %s ]\n" % (user, self.number))
self.lock.notifyAll()
def take_fork(self, user):
with self.lock:
while self.taken == True:
self.lock.wait()
self.user = user
self.taken = True
sys.stdout.write("Filozof[ %s ] podniósł widelec[ %s ]\n" % (user, self.number))
self.lock.notifyAll()
class Philosopher(threading.Thread):
def __init__(self, number, left, right, waiter):
threading.Thread.__init__(self)
self.number = number
self.left = left
self.right = right
self.waiter = waiter
def run(self):
for i in range(20):
self.waiter.down() #kelner
time.sleep(1) #myśli
self.left.take_fork(self.number) #bierze lewy widelec
time.sleep(1)
self.right.take_fork(self.number) #bierze prawy widelec
time.sleep(1) #je posiłek
self.right.drop_fork(self.number) #odkłada prawy widelec
self.left.drop_fork(self.number) #odkłada lewy widelec
self.waiter.up() #kelner
sys.stdout.write("-----Filozof[ %s ] skończył posiłek oraz dyskusję-----\n" % self.number)
class Deadlock(object):
def __init__(self, initial):
self.lock = threading.Condition(threading.Lock())
self.value = initial
def up(self):
with self.lock:
self.value += 1
self.lock.notify()
def down(self):
with self.lock:
while self.value == 0:
self.lock.wait()
self.value -= 1
forks = []
philosophers = []
waiter = Deadlock(4)
for i in range(0, 5):
forks.append(Fork(i))
for i in range(0, 5):
philosophers.append(Philosopher(i, forks[i], forks[(i+1)%5], waiter))
for i in range(5):
philosophers[i].start()
|
0e86001c06f024369bebf201f384609e526b2799 | KaPiech/Various-programs-Python | /Liczby_zespolone.py | 733 | 3.5625 | 4 | #Zadanie Liczby zespolone
import math
class Complex:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
def show_complex(self):
print(self.r, " + ", self.i, "i")
def conjugate(self):
self.i = -self.i
def module(self):
return math.sqrt((self.r * self.r) + (self.i * self.i))
def add(self, y):
return Complex(self.r + y.r, self.i + y.i)
def subtract(self, y):
return Complex(self.r - y.r, self.i - y.i)
def multiplicate(self, y):
return Complex(((self.r * y.r) - (self.i - y.i)), ((self.r * y.i) + (self.i * y.r)))
### przykład użycia ###
x = Complex(2.0, -2.0)
y = Complex(3, 5)
z1 = x.add(y)
z2 = x.subtract(y)
z3 = x.multiplicate(y)
z1.show_complex()
z2.show_complex()
z3.show_complex()
|
b86bc57163990cb644d6449b1e70a5eb435325b4 | Green-octopus678/Computer-Science | /Need gelp.py | 2,090 | 4.1875 | 4 | import time
import random
def add(x,y):
return x + y
def subtract(x,y):
return x - y
def multiply(x,y):
return x * y
score = 0
operator = 0
question = 0
#This part sets the variables for the question number, score and the operator
print('Welcome to my brilliant maths quiz\n')
time.sleep(1.5)
print()
print('What is your name?')
name = input('Name: ')
print()
print('Welcome to the quiz', name)
#This bit of the code asks for ther users name and then displays that name to the screen
time.sleep(2)
print('Which class are you in? A,B or C')
group = input('Class: ')
if group == 'A' or group == 'a':
file = open('Class_A_Results.txt', 'a')
if group == 'B' or group =='b':
file = open('Class_B_Results.txt', 'a')
if group == 'C' or group =='c':
file = open('Class_C_Results.txt', 'a')
#This bit of the code asks for ther users name and then displays that name to the screen
while question < 10:
#This part sets the number of questions to 10
n1 = random.randint(0,12)
n2 = random.randint(0, 12)
operator = random.randint (1,3)
#This bit of code sets the boundries for the random numbers and the operators
if operator == 1:
print(n1, "+", n2)
elif operator == 2:
print(n1, "-", n2)
elif operator == 3:
print(n1, "*", n2)
#This bit determines which operator is shown to the screen
if operator == 1:
ans = add(n1,n2)
elif operator == 2:
ans = subtract(n1,n2)
elif operator == 3:
ans = multiply(n1,n2)
#This part sets the answer to the question
answer = int(input())
if answer == ans:
print("Correct")
score = score + 1
else:
print("Incorrect")
question = question +1
#This part allows the user to put in an answer and tells them if they are right or not
print()
print()
print ('Score = ',score)
file.write(name)
file.write(':')
file.write(str(score))
file.write("\n")
file.close()
if score <=5:
print ('Unlucky')
else:
print('Well done')
#This part adds up the score and tells them the score and a message
|
3d323188aa765039b86b3149a8c512990447ff66 | Joanna-O-Ben/ADM-HW1 | /Problem1/Collections/Piling Up!.py | 367 | 3.734375 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
for t in range(int(input())):
input()
lst = [int(i) for i in input().split()]
min_list = lst.index(min(lst))
left = lst[:min_list]
right = lst[min_list+1:]
if left == sorted(left,reverse=True) and right == sorted(right):
print("Yes")
else:
print("No")
|
f59221aae91b469669e94313f89f4175022835ef | Joanna-O-Ben/ADM-HW1 | /Problem1/Strings/The Minion Game.py | 494 | 3.6875 | 4 | def minion_game(string):
# your code goes here
Stuart = 0
Kevin = 0
vowels = ["A", "E", "I", "O", "U"]
for l in range(len(string)):
if string[l] in vowels:
Kevin += len(string) - l
else:
Stuart += len(string) - l
if Kevin > Stuart:
print("Kevin " + str(Kevin))
elif Kevin < Stuart:
print("Stuart " + str(Stuart))
else:
print("Draw")
if __name__ == '__main__':
s = input()
minion_game(s) |
e82281f0a4886f667fc25dc42b42b7dd785b6681 | Joanna-O-Ben/ADM-HW1 | /Problem1/Built-Ins/ginortS.py | 652 | 3.953125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
S = list(input())
# print(S, type(S))
LETTERS = []
low = []
up = []
DIGITS = []
odd = []
even = []
for c in S:
if c.isalpha():
LETTERS.append(c)
if c.isnumeric():
DIGITS.append(c)
# print(LETTERS, DIGITS)
for s in LETTERS:
if s.isupper():
up.append(s)
else:
low.append(s)
# print(low, up)
for n in DIGITS:
n = int(n)
if n % 2 == 1:
n = str(n)
odd.append(n)
else:
n = str(n)
even.append(n)
# print(odd, even)
A = "".join(sorted(low) + sorted(up) + sorted(odd) + sorted(even))
print(A)
|
23af6db1effffb122dc991a8f83d2ac6a60bdc05 | Fari98/GA_learning_Snake | /past_versions/Davide/past version/snake_game_neuralnetwork.py | 8,428 | 3.546875 | 4 | #!/usr/bin/env python
# coding: utf-8
import pygame
import time
import random
import numpy as np
#DEFINIG 3 DISPLAY FUNCTIONS
def Your_score(score, yellow, score_font, dis):
value = score_font.render("Your Score: " + str(score), True, yellow)
dis.blit(value, [0, 0])
def our_snake(dis, black, snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block])
def message(msg, color, dis_width, dis_height, font_style, dis):
mesg = font_style.render(msg, True, color)
dis.blit(mesg, [dis_width / 6, dis_height / 3])
#MAIN GAME FUNCTION
def gameLoop(model, speed = 15, sight = 3, verbose = False):
#SETTINGS FOR DISPLAY
pygame.init()
white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
dis_width = 800
dis_height = 600
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('Shubham Snake Game')
clock = pygame.time.Clock()
snake_block = 10
snake_speed = speed
font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)
game_over = False
game_close = False
x1 = dis_width / 2
y1 = dis_height / 2
x1_change = 0
y1_change = 0
snake_List = []
Length_of_snake = 1
foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
#GAME LOOP
clock.tick(snake_speed)
#Initializing moves and age variables
moves = 0
age = 0
while not game_over:
#Preparing input for the NN
#distances to food
distance_food_y = foody - y1
distance_food_x = foodx - x1
#SCALE INPUTS to [0,1]
distance_food_y_scaled = (distance_food_y + (dis_height - snake_block))/(2*(dis_height - snake_block))
distance_food_x_scaled = (distance_food_x + (dis_width - snake_block))/(2*(dis_width - snake_block))
snake_head_x_scaled = x1 / (dis_width - snake_block)
snake_head_y_scaled = y1 / (dis_height - snake_block)
#VISION MATRIX
# Define a sight distance (number of squares counted from the
#edges of the snake's head; field of vision is a square as well)
sight_dist = sight
edge_length = 1+2*sight_dist
# Compute the "field of vision" of the snake; it is made up of
#a square array with the length of 1+2*sight_dist
# Side note: Possible positions in the game grid (without hitting
#the wall): Min: (0,0), Max: (790,590) - This is specified in snake.py
# Initialise a field of vision with all zeros
fov = np.zeros((edge_length, edge_length))
# Give the snake's head, snake_List, foodx, and foody shorter names
s_head = (x1, y1)
s_list = snake_List
fx, fy = (foodx, foody)
# Iterate over all elements of our field of vision array
for i in range(edge_length):
for j in range(edge_length):
# Decrement/increment our indices in such a way that they
#represent the relative position
rel_pos_x = j - sight_dist
rel_pos_y = i - sight_dist
# Get the values of the currently looked at field of vision element in our grid space
x = s_head[0] + rel_pos_x * snake_block
y = s_head[1] + rel_pos_y * snake_block
# Check if the currently looked at field of vision element contains a part of our snake
snake_body = [x, y] in s_list
# If so, write -1 in the respective field of vision cell
if snake_body:
fov[i,j] = -1
# Check if the currently looked at field of vision element is outside the allowed grid
outside_grid = x >= dis_width or x < 0 or y >= dis_height or y < 0
# If so, write -1 in the respective field of vision cell
if outside_grid:
fov[i,j] = -1
# Check if the currently looked at field of vision element contains food
food = (x == fx and y == fy)
# If so, write 1 in the respective field of vision cell
if food:
fov[i,j] = 1
#print(fov)
#Transorm input intpo np.array
input_nn = np.array( [distance_food_y_scaled, distance_food_x_scaled, #distances to food
snake_head_x_scaled, snake_head_y_scaled])#snake head
#Fixing the shape so it can be used for the NN
input_nn.shape = (1,4)
#Concatenating the vision matrix to the input array
fov.shape = (1,49)
input_nn = np.concatenate((input_nn, fov), axis = 1)
#Producing output of the model, the output are probabilities
#for each move, using np.argmax to get the index of the
#highest probability
output = np.argmax(model.predict(input_nn))
#print input and output through the game to check
#Increasing age and moves variables
age += 1
moves += 1
#After 50 moves without getting a fruit or dying the snake is 'stuck' therefore game is over
if moves == 300:
game_over = True
if verbose:
print(f'Input : {input_nn[:,:8]}')
print(f'Vision matrix : \n {fov}')
print(f'Output : {output}')
print(f'Moves : {moves}, age : {age}')
#COMMAND LOOP
for event in pygame.event.get():
#Command pad, moves the snake according to the output of the NN
if output == 0:
x1_change = -snake_block
y1_change = 0
#Adding random event to pygame.event queque to make it go
#further
event = pygame.event.Event(pygame.KEYDOWN, key=pygame.K_w)
pygame.event.post(event)
elif output == 1:
x1_change = snake_block
y1_change = 0
event = pygame.event.Event(pygame.KEYDOWN, key=pygame.K_w)
pygame.event.post(event)
elif output == 2:
y1_change = -snake_block
x1_change = 0
event = pygame.event.Event(pygame.KEYDOWN, key=pygame.K_w)
pygame.event.post(event)
elif output == 3:
y1_change = snake_block
x1_change = 0
event = pygame.event.Event(pygame.KEYDOWN, key=pygame.K_w)
pygame.event.post(event)
#CALCULATIONS OF OUTCOMES OF THE MOVE
if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
game_over = True #NEED TO CHANGE FOR FINAL VERSION
x1 += x1_change
y1 += y1_change
dis.fill(blue)
pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])
snake_Head = []
snake_Head.append(x1)
snake_Head.append(y1)
snake_List.append(snake_Head)
if len(snake_List) > Length_of_snake:
del snake_List[0]
for x in snake_List[:-1]:
if x == snake_Head:
game_over = True #NEED TO CHANGE FOR FINAL VERSION
our_snake(dis, black, snake_block, snake_List)
Your_score(Length_of_snake - 1, yellow, score_font, dis)
pygame.display.update()
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
Length_of_snake += 1
#Resetting moves to 0
moves = 0
pygame.quit()
return Length_of_snake, moves
|
6a2340a9996615d74e10bee8c872146e653e549e | gporceng/python-ordinal | /ordinals.py | 582 | 3.8125 | 4 | class OrdinalEngine:
def __init__(self):
pass
def ordinalize(self,x):
y=int(x)
if(x<11):
if(x==1):
return(str(x)+"st")
if(x==2):
return(str(x)+"nd")
if(x==3):
return(str(x)+"rd")
if(x>3):
return(str(x)+"th")
if(x>10 and x<20):
return(str(x)+"th")
#Find the exponent of 10
i=y
i/=10
i*=10
l=y
l-=i
if(x>19):
if(l==0):
return(str(x)+"th")
if(l==1):
return(str(x)+"st")
if(l==2):
return(str(x)+"nd")
if(l==3):
return(str(x)+"rd")
if(l>3):
return(str(x)+"th")
|
a5f3fdde75ca1ba377ace30608a3da5012bb5937 | itspratham/Python-tutorial | /Python_Contents/Python_Loops/BreakContinue.py | 443 | 4.21875 | 4 | # User gives input "quit" "Continue" , "Inbvalid Option"
user_input = True
while user_input:
user_input = str(input("Enter the valid input:"))
if user_input == "quit":
print("You have entered break")
break
if user_input == "continue":
print("You habe entered continue")
continue
print("Invalid input. Enter again")
print("Hello World")
print("Bye")
else:
print("Stoping the loop")
|
5732b9b78947a332125e21f441d20d73591a3f80 | itspratham/Python-tutorial | /Python_Contents/APAS/intersection_of_2_arrays.py | 181 | 3.703125 | 4 | def intersection(n1, n2):
l = []
for i in range(len(n1)):
if n1[i] in n2:
l.append(n1[i])
return l
print(intersection([4, 9, 5], [9, 4, 9, 8, 4]))
|
7563439f6f667bbe4c71a7256353dcf50de0ee8c | itspratham/Python-tutorial | /Python_Contents/data_structures/Stacks/stacks.py | 1,842 | 4.21875 | 4 | class Stack:
def __init__(self):
self.list = []
self.limit = int(input("Enter the limit of the stack: "))
def push(self):
if len(self.list) < self.limit:
x = input("Enter the element to be entered into the Stack: ")
self.list.append(x)
return f"{x} inserted into stack"
else:
return "Stack Overflow"
def pop(self):
if len(self.list) > 0:
return f"{self.list.pop()} is popped"
else:
return "Stack Underflow"
def disp(self):
return self.list
def Search_Element_in_the_Stack(self):
if len(self.list) == 0:
return "Stack is empty, Cannot find the element"
else:
print(self.list)
search_element = input("Enter the element to be searched: ")
for i in range(len(self.list)):
if search_element in self.list:
return f"Found the element at {i + 1}th position"
else:
return "Couldn't find the element in the stack"
def Delete_All_The_Elements_In_The_Stack(self):
if len(self.list) == 0:
return "Already Empty"
else:
self.list.clear()
return "The stack is empty now"
stack = Stack()
while True:
print(
"1:Push into the Stack 2:Pop from the Stack 3:Display 4:Enter the element you want to search in the Stack "
"5:Empty the stack 6:Exit")
op = int(input("Enter the option: "))
if op == 1:
print(stack.push())
elif op == 2:
print(stack.pop())
elif op == 3:
print(stack.disp())
elif op == 4:
print(stack.Search_Element_in_the_Stack())
elif op == 5:
print(stack.Delete_All_The_Elements_In_The_Stack())
else:
break
|
bd05b326c32c59a9e07132559e51435bf98c1aea | itspratham/Python-tutorial | /Python_Contents/data_structures/Pattern_Programming/Pattern_numbers/patterns_of_codes/pattern9.py | 131 | 3.515625 | 4 | g = 8
d = 9
for i in range(1, 10):
for j in range(i + g):
print(d, end=" ")
print(" ")
d = d - 1
g = g - 2
|
4c9b9f37153da03bba01f97011fe2619930726ea | itspratham/Python-tutorial | /Python_Contents/metaclass/eg4.py | 704 | 4.09375 | 4 | # the following variable would be set as the result of a runtime calculation:
x = input("Do you need the answer? (y/n): ")
if x == "y":
required = True
else:
required = False
def the_answer(self, *args):
return 42
class Philosopher1:
pass
if required:
Philosopher1.the_answer = the_answer
class Philosopher2:
pass
if required:
Philosopher2.the_answer = the_answer
class Philosopher3:
pass
if required:
Philosopher3.the_answer = the_answer
plato = Philosopher1()
kant = Philosopher2()
# let's see what Plato and Kant have to say :-)
if required:
print(kant.the_answer())
print(plato.the_answer())
else:
print("The silence of the philosphers") |
2bdc343f4849c59a59823ce162851b6fb846c280 | itspratham/Python-tutorial | /Python_Contents/data_structures/Array_Rearrangement/2.py | 413 | 4.34375 | 4 | # Write a program to reverse an array or string
# Input : arr[] = {1, 2, 3}
# Output : arr[] = {3, 2, 1}
#
# Input : arr[] = {4, 5, 1, 2}
# Output : arr[] = {2, 1, 5, 4}
def arrae(arr):
l1 = []
n = len(arr)
# i=0
# while i<n:
# l1.append(arr[n-i-1])
# n = n-1
for i in range(n):
l1.append(arr[-i-1])
return l1
arr = [1, 4, 7, 8, 6, 4, 5, 6]
print(arrae(arr))
|
c6ca7c13ca07e85f22cdc8a2114f4b82618dd03f | itspratham/Python-tutorial | /Python_Contents/OOP/SimpleInheritence/inheritence.py | 1,207 | 3.75 | 4 | class Human(object):
# Constructor
def __init__(self, name, age):
self.name = name
self.age = age
class Student(Human):
def __init__(self, name, age, total, avg):
super().__init__(name, age)
self.total = total
self.avg = avg
def display(self):
print("Name:{}".format(self.name))
print("Age:{}".format(self.age))
print("Total:{}".format(self.total))
print("Average:{}".format(self.avg))
# def __del__(self,total):
# self.total =total
s = Student("Jhon", 23, 500, 56)
s.display()
print(s.total)
#
#
# class Calculator:
# def __init__(self,total):
# self.total = total
# @classmethod
# def addNumbers(cls,data):
# cls.total = data
#
# f = Calculator(87)
# f.addNumbers(83)
# print(Calculator.total)
# arr = [7, 1, 2, 4]
# l = []
# n = len(arr)
# i = 0
#
# while i < n - 1:
# j = 0
# if arr[i] > arr[j + 1]:
# arr.remove(arr[i])
# n = n - 1
# print(arr)
# while j < n:
# print(arr[j], arr[i])
# if (arr[j] - arr[i]) > -1:
# l.append(arr[j] - arr[i])
# j = j + 1
# i = i + 1
# print(l)
# print(max(l))
|
5a9e775afdbb94c318be57ce4958b8b5ae55fc00 | itspratham/Python-tutorial | /Python_Contents/data_structures/Padma_Reddy/prg1.py | 2,774 | 3.96875 | 4 | # #Through Euclid's algorithm
# def gcd(m, n):
# while n != 0:
# r = m % n
# m = n
# n = r
#
# return m
#
#
# print(gcd(60, 200))
# Iterative approach
# def gcd(m,n):
# if n==0:
# return m
# return gcd(n, m%n)
#
# x = gcd(60,200)
# print(x)
# def gcd(m,n):
# while m !=n:
# if m>n:
# m = m-n
# else:
# n = n-m
#
# return m
# print(gcd(60, 200))
# to compute gcd using consecutive integer checking
# def gcd(m,n):
# small = min(m, n)
# while 1:
# if m % small == 0:
# if n % small == 0:
# return small
# small = small - 1
#
# print(gcd(60,200))
# Program for finding the largest number of an array
# l = [1,4,5,62,3,2,10,56]
# def largest(l):
# big = l[0]
# for i in range(1,len(l)-1):
# if l[i] > big:
# big = l[i]
# return big
#
# print(largest(l))
# Linear Search
# l= [83,3,4,5,434,3123,23133,442213]
#
# def linear_search(l):
# integer = int(input("Enter the number to be searched: "))
# for i in range(0,len(l)-1):
# if integer == l[i]:
# print(f"Number found at {i}")
# else:
# print("Number not found")
#
# return
#
# linear_search(l)
# Element uniqueness problem
# l = [4, 6, 7, 78, 3, 3, 2, 7, 6]
# l1 = [4, 6, 78, 3, 2, 7]
#
#
# def Element_uniqueness_problem(l):
# for i in range(0, len(l) - 2):
# for j in range(i + 1, len(l) - 1):
# if l[i] == l[j]:
# print(f"{l[i]} is present both at {i} and {j} position ")
#
# return f"The list is distinct"
# print(Element_uniqueness_problem(l))
# Element_uniqueness_problem(l1)
# Factorial Problem
# def factorial(n):
# if n==0:
# return 1
# elif n == 1:
# return 1
# else:
# return n*factorial(n-1)
#
# print(factorial(8))
# Multiplication of two matrices
# def Multiplication_of_two_matrices():
# Tower OF hanoi
# def towers(n, source, destination, spare):
# #count = 0
# if n == 1:
# print('move From', source, ' to destination ', destination)
# return 1
# else:
# #count += towers(n-1, source, spare, destination)
# towers(n - 1, source, spare, destination)
# #count += towers(1, source, destination, spare)
# print('move From', source, ' to destination ', destination)
# #count += towers(n-1, spare, destination, source)
# towers(n - 1, spare, destination, source)
# return
# print(towers(3, 'A', 'C', 'B'))
# Fibonacci Numbers
# def fibonacci(n):
# if n == 0:
# return 0
# elif n==1:
# return 1
# else:
# return fibonacci(n-1) + fibonacci(n-2)
#
# print(fibonacci(5))
|
04d31f088600732f14b74ad882fe4af4077f7ed5 | itspratham/Python-tutorial | /Python_Contents/File_Handling/file.py | 702 | 3.640625 | 4 | # x=open("hen.txt","r")
# #print(x.read(7))
# print(x.readlines())
# f = open("hen.txt", "r")
# for x in f:
# print(x)
# f = open("hen.txt", "a")
# f.write("Now the file has more content!")
# f.close()
# Assignment- Do it through loop
#
# f = open("hen.txt", "r")
# print(f.read())
# f = open("hen.txt", "w")
# f.write("Woops! I have deleted the content!")
# f.close()
# f=open("hen1.txt","x")
# f=open("E:\Python\python programs\Python\FirstProject\dog.txt","a")
# f.write("hello How are you")
# import os
# os.remove("E:\Python\python programs\Python\FirstProject\dog.txt")
f = open("hen.txt", "r")
filee = f.read()
fdf = filee.replace("'", '""')
g = open("hen.txt", "w")
g.write(fdf)
|
7ad142d38fdf39eb2098d84804c80fe60d9331d8 | itspratham/Python-tutorial | /Python_Contents/Sample_Programs/Array_DS/arr.py | 18,391 | 4.15625 | 4 | # Write a Python program to find the first duplicate element
# in a given array of integers.
# Return -1 If there are no such elements.
#
# def prog(arr):
# for i in range(len(arr)-1):
# for j in range(1,len(arr)):
# if arr[i] == arr[j]:
# return arr[i]
#
# print(prog([4,3,4,5,2,4,3]))
# def find_first_duplicate(nums):
# num_set = set()
# no_duplicate = -1
#
# for i in range(len(nums)):
#
# if nums[i] in num_set:
# return nums[i]
# else:
# num_set.add(nums[i])
#
# return no_duplicate
#
# print(find_first_duplicate([1, 2, 3, 4, 4, 5]))
# print(find_first_duplicate([1, 2, 3, 4]))
# print(find_first_duplicate([1, 1, 2, 3, 3, 2, 2]))
# Write a Python program to find whether a given array
# of integers contains any duplicate element.
# Return true if any value appears at least twice in the said array
# and return false if every element is distinct.
# def prog(arr):
# for i in range(len(arr)-1):
# for j in range(1,len(arr)):
# if arr[i] == arr[j]:
# return True
# return False
#
# print(prog([4,3,4,5,2,4,3]))
# def test_duplicate(array_nums):
# nums_set = set(array_nums)
# return len(array_nums) != len(nums_set)
# print(test_duplicate([1,2,3,4,5]))
# print(test_duplicate([1,2,3,4, 4]))
# print(test_duplicate([1,1,2,2,3,3,4,4,5]))
# Write a Python program to convert an array to an ordinary list with the same items.
# from array import *
# array_num = array('i', [1, 3, 5, 3, 7, 1, 9, 3])
# print("Original array: "+str(array_num))
# num_list = array_num.tolist()
# print("Convert the said array to an ordinary list with the same items:")
# print(num_list)
# Write a Python program to remove the first occurrence of a specified element from an array.
# l = [1,3,4,5,3,5]
# l.remove(5)
# print(l)
# n= 5
# for i in range(len(l)):
# if l[i]== n:
# l.remove(l[i])
# break
# print(l)
# Write a Python program to remove a specified item using the index from an array.
# from array import *
# array_num = array('i', [1, 3, 5, 7, 9])
# print("Original array: "+str(array_num))
# print("Remove the third item form the array:")
# array_num.pop(2)
# print("New array: "+str(array_num))
# 1. Write a python program to sort a numeric array and a string array.
#
#
# 2. Write a python program to sum values of an array.
#
#
#
# 3. Write a python program to print the following grid.
# Expected Output :
#
# - - - - - - - - - -
# - - - - - - - - - -
# - - - - - - - - - -
# - - - - - - - - - -
# - - - - - - - - - -
# - - - - - - - - - -
# - - - - - - - - - -
# - - - - - - - - - -
# - - - - - - - - - -
# - - - - - - - - - -
# for i in range(10):
# for j in range(10):
# print("-",end=" ")
# print()
# 4. Write a python program to calculate the average value of array elements.
# def arrayy(Arr):
# n =len(Arr)
# x =sum(Arr)
# print(x/n)
# arrayy([6,4,3,2,5,6,4,1,1,2,1,1])
# 5. Write a python program to test if an array contains a specific value.
# def arrayy(arr,specific):
# if specific in arr:
# return True
# return False
# print(arrayy([3,4,5,4,3,2,4,4],5))
# 6. Write a python program to find the index of an array element.
# def index(arr,element):
# for i in range(len(arr)):
# if arr[i] == element:
# return i+1
# print(index([3,1,2,5,7,10],10))
# 7. Write a python program to remove a specific element from an array.
# def specific_pgm(array,specific):
# for i in range(len(array)):
# if array[i] == specific:
# array.remove(array[i])
# break
# return array
# print(specific_pgm([2,3,4,2,5,6,7],2))
# 8. Write a python program to copy an array by iterating the array.
# def arr_iter(arr):
# new_arr = []
# for i in range(len(arr)):
# new_arr.append(arr[i])
# return new_arr
#
# print(arr_iter([3,4,5,6,7,3,7]))
# 9. Write a python program to insert an element (specific position) into an array.
# def arary(arr,specific,data):
# arr.insert(specific,data)
# return arr
# print(arary([2,4,2,1,5,6,7],4,9))
# 10. Write a python program to find the maximum and minimum value of an array.
# def max_min(arr):
# min =arr[0]
# max = arr[1]
# for i in range(len(arr)):
# if max> arr[i]:
# min = arr[i]
# else:
# max = arr[i]
# print("min:" ,min)
# print("Max:",max)
#
# max_min([5,3,7,2,9,1])
# 11. Write a python program to reverse an array of integer values.
# def reve(my_array1):
# for i in range(len(my_array1)//2):
# my_array1[i] ,my_array1[len(my_array1)- i - 1]= my_array1[len(my_array1)- i - 1],\
# my_array1[i];
#
# return my_array1
# print(reve([2,34,4,5,6,7,54,3,2,2,4,4]))
# 12. Write a python program to find the duplicate values of an array of integer values.
# def duplicate(arr):
# new = []
# for i in range(len(arr)):
# if arr[i] in arr[i+1:]:
# new.append(arr[i])
# return new
#
# print(duplicate([2,6,4,3,2,8,4,6]))
# 13. Write a python program to find the duplicate values of an array of string values.
# def duplicate(arr):
# new = []
# for i in range(len(arr)):
# if arr[i] in arr[i+1:]:
# new.append(arr[i])
# return new
#
# print(duplicate(["hello","humpty","Dumpty","hello"]))
# 14. Write a python program to find the common elements between two arrays (string values).
# def common_elements(arr1,arr2):
# common = []
# for i in range(len(arr1)):
# if arr1[i] in arr2:
# if arr1[i] not in common:
# common.append(arr1[i])
# return common
# print(common_elements([2,34,5,6,7,2,6,8],[1,2,3,4,5,6,7]))
# 15. Write a python program to find the common elements between two arrays of integers.
#
#
#
# 16. Write a python program to remove duplicate elements from an array.
# Python code to remove duplicate elements
# def Remove(duplicate):
# final_list = []
# for num in duplicate:
# if num not in final_list:
# final_list.append(num)
# return final_list
#
# duplicate = [2, 4, 10, 20, 5, 2, 20, 4]
# print(Remove(duplicate))
# 17. Write a python program to find the second largest element in an array.
# 18. Write a python program to find the second smallest element in an array.
# def second(arr):
# for i in range(0,len(arr)):
# for j in range(i+1,len(arr)):
# if arr[i]> arr[j]:
# temp = arr[i]
# arr[i] = arr[j]
# arr[j] = temp
# return arr[1]
# print(second([2,5,4,8,97,3,56]))
# 19. Write a python program to add two matrices of the same size.
# l = [[1,2],
# [3,4]]
# l1 = [[1,2],
# [3,4]]
# copy=[]
# for i in range(len(l)):
# for j in range(len(l)):
# copy.append(l[i][j]+l[i][j])
#
# print(copy)
# 20. Write a python program to convert an array to ArrayList.
# no need
#
#
# 21. Write a python program to convert an ArrayList to an array.
#
# no need
#
# 22. Write a python program to find all pairs of elements in an array
# whose sum is equal to a specified number.
# arr = [2, 3, -5, 5, 2, 7, 8, 6, 16]
# f = 11
# for i in range(len(arr)):
# for j in range(i + 1):
# if arr[i] + arr[j] == f:
# print(f"{arr[i]} + ({arr[j]}) = {f}")
# 23. Write a python program to test the equality of two arrays.
# def equality(arr1, arr2):
# f = True
# for i in range(len(arr1)):
# for j in range(len(arr2)):
# if arr1[i] != arr2[j]:
# f = False
# else:
# f = True
# return f
#
#
# print(equality([1, 2, 3, 4, 5], [1, 2, 3, 4, 5]))
# 24. Write a python program to find a missing number in an array.
#
#
#
# 25. Write a python program to find common elements from three sorted
# (in non-decreasing order) arrays.
#
#
#
# 26. Write a python program to move all 0's to the end of an array.
# Maintain the relative order of the other (non-zero) array elements.
#
#
#
# 27. Write a python program to find the number of even and odd integers in a given array
# of integers.
# can be dne
# 28. Write a python program to get the difference between the largest and smallest
# values in an array of integers. The length of the array must be 1 and above.
# def largest_smallest(arr):
# maxx = arr[0]
# minn = arr[1]
# for i in range(len(arr)):
# if minn > arr[i]:
# minn = arr[i]
# else:
# maxx = arr[i]
# return maxx - minn
#
#
# print(largest_smallest([2, 4, 1, 3, 4, 5, 9, 88]))
# 29. Write a python program to compute the average value of an array of integers
# except the largest and smallest values.
# def largest_smallest(arr):
# maxx = arr[0]
# minn = arr[1]
# for i in range(len(arr)):
# for j in range(i + 1, len(arr)):
# temp = arr[i]
# arr[i] = arr[j]
# arr[j] = temp
#
#
# print(largest_smallest([2, 4, 1, 3, 4, 5, 9, 88]))
# 30. Write a python program to check if an array of integers without 0 and -1.
#
# can be done
#
# 31. Write a python program to check if the sum of all the 10's in the array is exactly 30.
# Return false if the condition does not satisfy, otherwise true.
# def tens(arr):
# count = 0
# for i in range(len(arr)):
# if arr[i] == 10:
# count += 1
# if count != 3:
# print("False")
# else:
# print("True")
#
#
# tens([4, 5, 6, 10, 7, 10, 8, 10, 10])
# 32. Write a python program to check if an array of integers contains
# two specified elements 65 and 77.
# can be done
# 33. Write a python program to remove the duplicate elements of a given array and
# return the new length of the array.
# Sample array: [20, 20, 30, 40, 50, 50, 50]
# After removing the duplicate elements
# the program should return 4 as the new length of the array.
# def duplicates(arr):
# new = []
# for i in range(len(arr)):
# if arr[i] not in new:
# new.append(arr[i])
#
# return len(new)
#
#
# print(duplicates([20, 20, 30, 40, 50, 50, 50]))
# 34. Write a python program to find the length of the longest consecutive elements
# sequence from a given unsorted array of integers.
# Sample array: [49, 1, 3, 200, 2, 4, 70, 5]
# The longest consecutive elements sequence is [1, 2, 3, 4, 5],
# therefore the program will return its length 5.
# 35. Write a python program to find the sum of the two elements of a given array
# which is equal to a given integer.
# Sample array: [1,2,4,5,6]
# Target value: 6.
#
#
#
# 36. Write a python program to find all the unique triplets such that sum of all the three elements [x, y,
# z (x ≤ y ≤ z)] equal to a specified number. Sample array: [1, -2, 0, 5, -1, -4] Target value: 2.
#
#
#
# 37. Write a python program to create an array of its anti-diagonals from a given square matrix.
#
# Example:
# Input :
# 1 2
# 3 4
# Output:
# [
# [1],
# [2, 3],
# [4]
# ]
# l = [[1, 2],
# [3, 4], [5, 6]]
#
#
# def anti_diagmnoal(l):
# copy = []
# for i in range(len(l)):
# for j in range(i + 1):
# copy.append([l[i][j:]])
# copy.append([l[i][len(l) - j - 1]])
# return copy
#
#
# print(anti_diagmnoal(l))
# 38. Write a python program to get the majority element from a given array of integers
# containing duplicates.
# Majority element: A majority element is an element
# that appears more than n/2 times where n is the size of the array.
#
#
#
# 39. Write a python program to print all the LEADERS in the array.
# Note: An element is leader if it is greater than all the elements to its right side.
# def leader(string):
# d = []
# for i in range(len(string)):
# d.append(string[i])
# return d
#
# print(leader("leader"))
# 40. Write a python program to find the two elements from a given array
# of positive and negative numbers such that their sum is closest to zero.
# def zero(arr):
# pass
# 41. Write a python program to find smallest and second-smallest elements of a given array.
# def second(arr):
# for i in range(0,len(arr)):
# for j in range(i+1,len(arr)):
# if arr[i]> arr[j]:
# temp = arr[i]
# arr[i] = arr[j]
# arr[j] = temp
# return arr[0],arr[1]
# print(second([2,5,4,8,97,3,56]))
# 42. Write a python program to segregate all 0s on left side and
# all 1s on right side of a given array of 0s and 1s.
#
#
#
# 43. Write a python program to find all combination of four elements of a given array
# whose sum is equal to a given value.
#
#
#
# 44. Write a python program to count the number of possible triangles
# from a given unsorted array of positive integers.
# def possible_triangles(arr):
# count = 0
# for i in range(0, len(arr)):
# for j in range(i + 1, len(arr)):
# for k in range(i + 1, len(arr)):
# if (arr[i] + arr[j] > arr[k] & arr[i] + arr[k] > arr[j]
# & arr[k] + arr[j] > arr[i]):
# count += 1
#
# return count
#
#
# print(possible_triangles([2, 3, 4, 5, 6, 7]))
# 45. Write a python program to cyclically rotate a given array clockwise by one.
# def cyclically(arr):
# rotated = []
# for i in range(len(arr)):
# temp = arr[0]
# for j in range(len(arr)):
# 46 Write a python program to check whether there is a pair
# with a specified sum of a given sorted and rotated array.
# 47. Write a python program to find the rotation count in a given rotated sorted array
# of integers.
# def rotated(arr):
# min_value = arr[0]
# min_index = -1
# for i in range(1, len(arr)):
# if min_value > arr[i]:
# min_value = arr[i]
# min_index = i
# return min_index, arr
#
#
# print(rotated([35, 32, 30, 14, 18, 21, 27]))
# 48. Write a python program to arrange the elements of a given array of integers
# where all negative integers appear before all the positive integers.
#
# done
#
# 49. Write a python program to arrange the elements of a given array of integers
# where all positive integers appear before all the negative integers.
# can be done
# 50. Write a python program to sort an array of positive integers of a given array,
# in the sorted array the value of the first element should be maximum,
# second value should be minimum value, third should be second maximum,
# fourth second be second minimum and so on.
# def rearrange(arr, n):
# # Auxiliary array to hold modified array
# temp = n * [None]
#
# # Indexes of smallest and largest elements
# # from remaining array.
# small, large = 0, n - 1
#
# # To indicate whether we need to copy rmaining
# # largest or remaining smallest at next position
# flag = True
#
# # Store result in temp[]
# for i in range(n):
# if flag is True:
# temp[i] = arr[large]
# large -= 1
# else:
# temp[i] = arr[small]
# small += 1
#
# flag = bool(1 - flag)
#
# # Copy temp[] to arr[]
# for i in range(n):
# arr[i] = temp[i]
# return arr
#
#
# # Driver program to test above function
# arr = [1, 2, 3, 4, 5, 6]
# n = len(arr)
# print("Original Array")
# print(arr)
# print("Modified Array")
# print(rearrange(arr, n))
# 51. Write a python program to separate 0s on left side
# and 1s on right side of an array of 0s and 1s in random order.
# def even_odd(a):
# l = []
# for i in range(len(a)):
# if a[i] == 0:
# l.append(a[i])
# for i in range(len(a)):
# if a[i] != 0:
# l.append(a[i])
# return l
#
#
# print(even_odd([1, 0, 1, 0, 1, 0, 0, 0, 1, 0]))
# 52. Write a python program to separate even and
# odd numbers of a given array of integers.
# Put all even numbers first, and then odd numbers.
# def even_odd(a):
# l = []
# for i in range(len(a)):
# if a[i] % 2 == 0:
# l.append(a[i])
# for i in range(len(a)):
# if a[i] % 2 != 0:
# l.append(a[i])
# return l
#
#
# print(even_odd([3, 6, 7, 4, 5, 6, 7, 0]))
# 53. Write a python program to replace every element with the next greatest
# element (from right side) in a given array of integers.
# def greatest(arr):
# dup = []
# for i in range(len(arr) - 1):
# dup.append(max(arr[i + 1:]))
# return dup
#
#
# print(greatest([45, 20, 100, 23, -5, 2, -6]))
# def sortt(arr):
# for i in range(0, len(arr) - 1):
# index = i
# for j in range(i + 1, len(arr)):
# if arr[index] > arr[j]:
# index = j
# arr[i], arr[index] = arr[index], arr[i]
# return arr
#
#
# print(sortt([4, 2, 6, 3, 9, 5, 3, 8, 6]))
# def sort(a):
# for i in range(len(a) - 1):
# for j in range(i + 1, len(a)):
# if a[i] > a[j]:
# temp = a[i]
# a[i] = a[j]
# a[j] = temp
#
# return a
#
#
# print(sort([8, 4, 6, 10, 6, 9]))
# Triplet problems
#
# limit = int(input("Enter upper limit:"))
# c = 0
# m = 2
# while c < limit:
# for n in range(1, m + 1):
# a = m * m - n * n
# b = 2 * m * n
# c = m * m + n * n
# if c > limit:
# break
# if a == 0 or b == 0 or c == 0:
# break
# print(a, b, c)
# m = m + 1
|
aca6dd1cca7a053e1b6f9e7bc0408d50e3ddd372 | itspratham/Python-tutorial | /Python_Contents/data_structures/recursion/prg2.py | 2,776 | 3.625 | 4 | # Replace every array element with the product of every other element
# without using a division operator
# Input: {1, 2, 3, 4, 5}
# Output: {120, 60, 40, 30, 24}
#
# Input: {5, 3, 4, 2, 6, 8}
# Output: {1152, 1920, 1440, 2880, 960, 720}
# def multiply(arr1, arr2):
# sol = arr1 + arr2
# mul = 1
# for i in range(len(sol)):
# mul = mul * sol[i]
# return mul
#
#
# def a_func(arr):
# a_list = []
# for i in range(len(arr)):
# num = multiply(arr[:i], arr[i + 1:])
# a_list.append(num)
# return a_list
#
#
# print(a_func([5, 3, 4, 2, 6, 8]))
# Find all distinct combinations of a given length – I
# Given an integer array, find all distinct combinations
# of a given length k.
# For
# example,
#
# Input: {2, 3, 4}, k = 2
# Output: {2, 3}, {2, 4}, {3, 4}
#
# Input: {1, 2, 1}, k = 2
# Output: {1, 2}, {1, 1}, {2, 1}
# Function to print all distinct combinations of length `k`
# def findCombinations(A, n, k, subarrays, out=()):
# # invalid input
# if len(A) == 0 or k > n:
# return
#
# # base case: combination size is `k`
# if k == 0:
# subarrays.add(out)
# return
#
# # start from the next index till the first index
# for i in reversed(range(n)):
# # add current element `A[i]` to the output and recur for next index
# # `i-1` with one less element `k-1`
# findCombinations(A, i, k - 1, subarrays, (A[i],) + out)
#
#
# def getDistinctCombinations(A, k):
# subarrays = set()
# findCombinations(A, len(A), k, subarrays)
# return subarrays
#
#
# if __name__ == '__main__':
# A = [1, 2, 3]
# k = 2
#
# # process elements from right to left
# subarrays = getDistinctCombinations(A, k)
# print(subarrays)
# Python 3 program for recursive binary search.
# Modifications needed for the older Python 2 are found in comments.
# Returns index of x in arr if present, else -1
def binary_search(arr, low, high, x):
# Check base case
if high >= low:
mid = (high + low) // 2
# If element is present at the middle itself
if arr[mid] == x:
return mid + 1
# If element is smaller than mid, then it can only
# be present in left subarray
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)
# Else the element can only be present in right subarray
else:
return binary_search(arr, mid + 1, high, x)
else:
# Element is not present in the array
return -1
# Test array
arr = [2, 3, 4, 10, 40]
x = 10
# Function call
result = binary_search(arr, 0, len(arr) - 1, x)
if result != -1:
print("Element is present at index:", str(result))
else:
print("Element is not present in array")
|
57e8f174c09cd06a6a0bce3c31bfb878426dc887 | itspratham/Python-tutorial | /Python_Contents/APAS/recursion/prg1.py | 1,490 | 4.03125 | 4 | # Swap Nodes in Pairs
# Given a linked list, swap every two adjacent nodes and return its head.
# You must solve the problem without modifying the values in the list's nodes
# (i.e., only nodes themselves may be changed.)
# Example 1:
# Input: head = [1,2,3,4]
# Output: [2,1,4,3]
# Example 2:
#
# Input: head = []
# Output: []
# Example 3:
#
# Input: head = [1]
# Output: [1]
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_Data = Node(data)
if self.head is None:
self.head = Node(data)
return
cur_node = self.head
while cur_node.next:
cur_node = cur_node.next
cur_node.next = new_Data
def print_Data(self):
if self.head is None:
return "Empty List"
cur_node = self.head
while cur_node:
print(cur_node.data)
cur_node = cur_node.next
return
def Swap_Nodes_in_Pairs(self):
if self.head is None:
return []
cur_node = self.head
while cur_node and cur_node.next:
first_node = cur_node
second_node = cur_node.next
second_node.next = first_node
first_node.next = second_node
ll = LinkedList()
ll.append("A")
ll.append("B")
ll.append("C")
ll.append("D")
ll.print_Data()
ll.Swap_Nodes_in_Pairs()
ll.print_Data() |
b8681e5d210cc1d5d5c36824ec627eaffc9b1db6 | itspratham/Python-tutorial | /Python_Contents/Pythonfunctions/simpleFunctions.py | 435 | 3.546875 | 4 | ## Function:
"""
def function_name(<varaibel1>,<varaibel1>):
statement1
statement2
return value
file.write()
"""
def minus(a, b):
print(a - b)
def add(a, b):
return a + b
print("The function returns {}".format(minus(12, 5)))
print("The function returns {}".format(add(12, 5)))
print("Calling minus")
minus(12, 5)
print(add(12, 34))
x, y = 100, 150
print(add(x, y))
sum = add(129923, 221323)
print(sum)
|
e0aa179b5acfc5514224e99d6a1a9eea7491c526 | itspratham/Python-tutorial | /Python_Contents/data_structures/Pattern_Programming/Pattern_numbers/patterns_of_codes/pattern20.py | 210 | 3.78125 | 4 | n = 5
for i in range(1, n + 1):
temp = i
for j in range(1, n + 1):
print(temp, end=" ")
temp = temp + 1
if temp >= n + 1:
temp = 1
print(" ")
temp = temp - 2
|
915c9204911082e9b78205172985f037b99b9f3a | itspratham/Python-tutorial | /Python_Contents/APAS/median_two_array.py | 1,619 | 3.78125 | 4 | # def median_of_two_sorted_array(a1,a2):
# final = sorted(a1+a2)
# if len(final)%2==1:
# return final[len(final)//2]
# else:
# d= final[(len(final)//2)-1] + final[(len(final)//2)]
# return d/2
#
# print(median_of_two_sorted_array([1,2,90754,98],[3,4.7574,86]))
# Input : arr[] = {2, 5, 8, 4, 6, 11}, sum = 13
# Output :
# 5 8
# 2 11
# 2 5 6
#
# Input : arr[] = {1, 5, 8, 4, 6, 11}, sum = 9
# Output :
# 5 4
# 1 8
# def print_all_subsets(arr,target):
# l = []
# for i in range(len(arr)):
# for j in range(len(arr)):
# temp = arr[j]
# if arr[i] + temp < target:
# l.append([arr[i],arr[j]])
#
#
# print_all_subsets([3,4,5,3])
# Return true if there exists a sublist of A[0..n] with given sum
def subsetSum(A, n, sum):
# return true if sum becomes 0 (subset found)
if sum == 0:
return True
# base case: no items left or sum becomes negative
if n < 0 or sum < 0:
return False
# Case 1. include current item in the subset (A[n]) and recur
# for remaining items (n - 1) with remaining sum (sum - A[n])
include = subsetSum(A, n - 1, sum - A[n])
# Case 2. exclude current item n from subset and recur for
# remaining items (n - 1)
exclude = subsetSum(A, n - 1, sum)
# return true if we can get subset by including or excluding the
# current item
return include or exclude
# Subset Sum Problem
if __name__ == '__main__':
# Input: set of items and a sum
A = [7, 3, 2, 5, 8]
sum = 14
print("Yes" if subsetSum(A, len(A) - 1, sum) else "No")
|
f7f08524e4dcc33fa16ba5d9d9216f0d2136c262 | itspratham/Python-tutorial | /Python_Contents/data_structures/Pattern_Programming/Pattern_numbers/patterns_of_codes/pattern10.py | 273 | 3.671875 | 4 | j = 0
count = 1
n = 5
for i in range(1, 6):
for k in range(i):
print(count, end=' ')
count = count + 1
temp = count
count = count - 2
for k in range(1, i):
print(count, end=' ')
count = count - 1
count = temp
print()
|
451d63d075056e056820a5582bd71cf98b60386c | itspratham/Python-tutorial | /Python_Contents/Caw Studios/prg1.py | 778 | 3.96875 | 4 | # Input: s = "leEeetcode" Output: "leetcode"
# Explanation: In the first step, either you choose i = 1 or i = 2,
# both will result "leEeetcode" to be reduced to "leetcode".
# Input: s = "abBAcC"
# Output: ""
# Explanation: We have many possible scenarios, and all lead to the same answer. For example:
# "abBAcC" --> "aAcC" --> "cC" --> ""
# "abBAcC" --> "abBA" --> "aA" --> ""
# Input: s = "s"
# Output: "s"
# gg = "dd"
# gg.rep
def check_the_String(stringg):
extra_string = ''
count = 0
while len(stringg)+1 > count:
if ord(stringg[count]) == ord(stringg[count + 1]) - 26:
pass
else:
extra_string = extra_string + stringg[count]
count = count + 1
return extra_string
print(check_the_String("leeEtCode"))
|
2862b4d9c0d64e553e2a4c49ee80700025a6756b | itspratham/Python-tutorial | /Python_Contents/APAS/zigzag.py | 708 | 3.53125 | 4 | def convert(s, numRows):
if s is None:
return s
if numRows == 0:
return s
if numRows == 1:
return s
rstr = ""
for i in range(numRows):
if i == 0:
rstr += s[::numRows + (numRows - 2)]
elif i == numRows - 1:
rstr += s[i::numRows + (numRows - 2)]
else:
spacea = 2 * (numRows - i)
spaceb = 2 * i
counter = 0
j = i
while j < len(s):
rstr += s[j]
if counter % 2 == 0:
j += spacea
else:
j += spaceb
counter += 1
return rstr
print(convert("abcdefg", 2))
|
59fa0a1e50a49f472b1cc08f97e1707f6a86b85b | itspratham/Python-tutorial | /Python_Contents/problems/10.py | 280 | 3.96875 | 4 | """
Write a Python program that accepts an integer (n) and computes the value of n+nn+nnn.
Sample value of n is 5
Expected Result : 615
Click me to see the sample solution
"""
n = int(input("Sample value of n is: "))
print(f"The value of n+nn+nnn = {n + (n * n) + (n * n * n)}")
|
55c7cdd0b1907010883f3e07a1f68dfa48604140 | itspratham/Python-tutorial | /Python_Contents/Sample_Programs/linked_list.py | 5,078 | 4.09375 | 4 | # class Node:
# def __init__(self,data):
# self.data = data
# self.next = None
#
# class LinkedList:
# def __init__(self):
# self.head = None
#
# def append(self,data):
# if self.head is None:
# self.head = Node(data)
# return
# cur_node = self.head
# new_node = Node(data)
# while cur_node.next:
# cur_node = cur_node.next
# cur_node.next =new_node
#
#
# def print_list(self):
# currnode = self.head
# while currnode:
# print(currnode.data)
# currnode = currnode.next
#
# def delete_node(self,key):
# if self.head is None:
# print("No scope to delete the node")
# return
# curr_node = self.head
# if curr_node.data == key:
# self.head = curr_node.next
# curr_node = None
# return
#
# prev = None
# while curr_node.data and curr_node.data != key:
# prev = curr_node
# curr_node = curr_node.next
#
# prev.next = curr_node.next
# curr_node = None
#
# def insert_at_an_index(self,position,data):
# newnode = Node(data)
# if self.head is None:
# print("List is empty and I can insert for you at 1st position")
# self.append(data)
# return
# curr_node = self.head
# if self.head.next is None and position == 1:
# self.head = newnode
# newnode.next = curr_node
# return
# prev = None
# count = 1
# while count<position:
# prev = curr_node
# curr_node = curr_node.next
# count = count+1
# prev.next = newnode
# newnode.next = curr_node
#
# def rotate_left(self,position):
# if self.head is None and position<=0:
# return
# if self.head and position==1:
# return
#
# headd = self.head
# curr_node = self.head
# prev = None
# count = 0
# while curr_node and count<position:
# prev = curr_node
# headd = headd.next
# curr_node = curr_node.next
# count = count + 1
# curr_node = prev
#
# while headd:
# prev =headd
# headd = headd.next
#
# headd = prev
# headd.next = self.head
# self.head = curr_node.next
# curr_node.next = None
#
# def prepend(self,data):
# if self.head == None:
# self.head = Node(data)
# self.head.next = None
# return
# newnode = Node(data)
# curnode = self.head
# self.head = newnode
# newnode.next = curnode
#
# l = LinkedList()
# l.append("A")
# l.prepend("B")
# l.append("C")
# l.append("D")
# l.append("E")
# l.print_list()
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
if self.head is None:
self.head = Node(data)
return
newnode = Node(data)
cur_node = self.head
while cur_node.next:
cur_node = cur_node.next
cur_node.next = newnode
def print_list(self):
curnode = self.head
while curnode:
print(curnode.data)
curnode = curnode.next
def prepend(self, data):
if self.head is None:
self.head = Node(data)
return
newnode = Node(data)
curnode = self.head
self.head = newnode
newnode.next = curnode
def length(self):
if self.head is None:
return 0
curnode = self.head
count = 1
while curnode.next:
count = count + 1
curnode = curnode.next
return count
def middle_ele(self):
count = self.length()
position = count // 2
curnode = self.head
countt = 1
while countt < position:
curnode = curnode.next
countt += 1
return curnode.next.data
def sortList(self):
# swap = 0
if self.head != None:
while (1):
swap = 0
tmp = self.head
while tmp.next is not None:
if tmp.data > tmp.next.data:
# swap them
swap += 1
p = tmp.data
tmp.data = tmp.next.data
tmp.next.data = p
tmp = tmp.next
else:
tmp = tmp.next
if swap == 0:
break
else:
continue
return self.head
else:
return self.head
ll = LinkedList()
ll.append(1)
ll.append(2)
# ll.prepend(3)
ll.append(5)
ll.append(87)
# ll.prepend(89)
# ll.sortList()
ll.print_list()
|
1c92251342d8af5183a31dd0d3bcff67fca50a81 | itspratham/Python-tutorial | /Python_Contents/Python_Decision_Statements/IfElseif.py | 333 | 4.15625 | 4 | # Time 00 to 23
# Input the time from the user
tm = int(input("Enter the time:"))
if 6 < tm < 12:
print("Good Morning")
elif 12 < tm < 14:
print("Good Afternoon")
elif 14 < tm < 20:
print("Good Evening")
elif 20 < tm < 23:
print("Good Night")
elif tm < 6:
print("Early Morning")
else:
print("Invalid time")
|
b12ba761572bb1ba3d56eb66fadf089b490e94a9 | Triple-L/Wartegg_test | /Test/T_python_fitline_最小二乘.py | 1,124 | 3.71875 | 4 | #python 最小二乘拟合直线
# -*- coding: utf-8 -*
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 30, num=50)
y = 0.2*x+[np.random.random() for _ in range(50)]
if __name__ == '__main__':
plt.figure(figsize=(10, 5), facecolor='w')
plt.plot(x, y, 'ro', lw=2, markersize=6)
plt.grid(b=True, ls=':')
plt.xlabel(u'X', fontsize=16)
plt.ylabel(u'Y', fontsize=16)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
def Least_squares(x,y):
x_ = x.mean()
y_ = y.mean()
m = np.zeros(1)
n = np.zeros(1)
k = np.zeros(1)
p = np.zeros(1)
for i in np.arange(50):
k = (x[i]-x_)* (y[i]-y_)
m += k
p = np.square( x[i]-x_ )
n = n + p
a = m/n
b = y_ - a* x_
return a,b
if __name__ == '__main__':
a,b = Least_squares(x,y)
print(a,b)
y1 = a * x + b
plt.figure(figsize=(10, 5), facecolor='w')
plt.plot(x, y, 'ro', lw=2, markersize=6)
plt.plot(x, y1, 'r-', lw=2, markersize=6)
plt.grid(b=True, ls=':')
plt.xlabel(u'X', fontsize=16)
plt.ylabel(u'Y', fontsize=16)
plt.show()
|
ac328151d8868822f0f952fd1203b6cd00b0e097 | loicmidy/formation-python | /ressources data science/ensemble/conversions.py | 1,843 | 3.5625 | 4 | # -*- coding: utf-8 -*-
import pandas as pd
notesElevesMatières=pd.read_csv('C:/Users/loicm/ressources data science/ensemble/eleves.csv',sep="|",
dtype={'élève':str,
'moyenneMath':float,
'moyennePhysique':str,
'sexe':str,
'dateNaissance':str,
'PCS':int})
print(notesElevesMatières.info())
#1 : conversion avec astype()
notesElevesMatières['PCS']=notesElevesMatières['PCS'].astype('int16')#car astype retourne une copie
print(notesElevesMatières.info())
#2 : conversion avec fonction ad hoc
def convertirvariableSexe(sexe):
if sexe=="H":return 1
else: return 2
notesElevesMatières['sexe']=notesElevesMatières['sexe'].apply(convertirvariableSexe)
print(notesElevesMatières.info())
#3 : conversion avec to_numeric() et to_datetime()
notesElevesMatières['moyennePhysique']=pd.to_numeric(notesElevesMatières['moyennePhysique'], errors='coerce')
"""
errors ='raise' => the default and will generate an error on something like [1,2,'apple'].
errors ='ignore' => the problem values will not be converted at all.
errors ='coerce' => force the column to float and problem values to NaN
"""
print(notesElevesMatières.info())
notesElevesMatières['dateNaissance']= pd.to_datetime(notesElevesMatières['dateNaissance'], format='%d%m%Y', errors='coerce')
notesElevesMatières['jourNaissance'] = pd.DatetimeIndex(notesElevesMatières['dateNaissance']).day
notesElevesMatières['moisNaissance'] = pd.DatetimeIndex(notesElevesMatières['dateNaissance']).month
notesElevesMatières['annéeNaissance'] = pd.DatetimeIndex(notesElevesMatières['dateNaissance']).year
print(notesElevesMatières.info())
|
efcb316380076d0836d4f0f537df9d5aa94d8b66 | kuzxnia/algoritms | /brain_training/programming_challenges/euler/T006.py | 219 | 3.625 | 4 | def sum_square_difference():
def _squares_sum():
return sum([x**2 for x in range(1, 101)])
def _sum_square():
return sum([x for x in range(1, 101)])**2
return _sum_square() - _squares_sum() |
6ee7b86e0b5a838f7ac4657e5db72f47c8ff8e85 | kuzxnia/algoritms | /brain_training/programming_challenges/euler/T007.py | 365 | 3.796875 | 4 | import math
def ten_thousand_one_prime():
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
prime_amount = 1
number = 3
while prime_amount != 10001:
if is_prime(number):
prime_amount += 1
number += 2
return number - 2
|
c91b8d31cdd4da012183f9f84dae7f438a5e6dd2 | kuzxnia/algoritms | /brain_training/programming_challenges/src/T018/anagram.py | 126 | 3.875 | 4 | def is_anagram(word1, word2):
if len(word1) != len(word2):
return False
return sorted(word1) == sorted(word2) |
425c505c10a4b6020df0b4c65878b83aa39399d0 | kuzxnia/algoritms | /computer_science/algoritms/search/linearsearch.py | 160 | 3.78125 | 4 | # Big O complexity
# O(n)
def linearSearch(arg, arr):
for i in range(len(arr)):
if arr[i] == arg:
return i
else:
return -1
|
79f0af0443d62be98721a88646fa68b2fb4682cb | kobbyopoku/tic-tac-toe | /functions.py | 1,478 | 3.875 | 4 | students = []
def get_students_titlecase():
students_titlecase = []
for student in students:
students_titlecase.append(student["name"].title())
return students_titlecase
def print_student_titlecase():
students_titlecase = get_students_titlecase()
print(students_titlecase)
def add_student(name, student_id=1):
student = {"name": name, "student_id": student_id}
students.append(student)
def save_file(student):
try:
f = open("student.txt", "a")
f.write(student + "\n")
f.close()
except Exception:
print("could not save file")
def read_file():
try:
f = open("student.txt", "r")
for student in read_students(f):
add_student(student)
f.close()
except Exception:
print("could not read file")
def read_students(f):
for line in f:
yield line
# add_student(name="Kay")
def var_args(name, *args):
print(name)
print(args)
def var_kwargs(name, **kwargs):
print(name)
print(kwargs["description"], kwargs["age"], kwargs["feedback"])
# var_args("Kobby", "loves Python3", 23, None)
# var_kwargs("Kobby", description="loves Python3", age=23, feedback=None)
# student_list = get_students_titlecase()
read_file()
print_student_titlecase()
student_name = input("Enter student name: ")
student_id = input("Enter student ID: ")
add_student(student_name, student_id)
save_file(student_name)
# print_student_titlecase()
|
1d0611e0addd37b212419b0323e1f5832d101b2f | omkarpoudel6/guicalculator | /calculator.py | 2,650 | 3.796875 | 4 | from tkinter import *
print("calculator")
def calculate(a):
try:
z=eval(a)
input.set(z)
except:
input.set("Error!!!")
root=Tk()
root.title("Calculator")
root.geometry("250x150")
root.resizable(0,0)
input=StringVar()
Entry(root,background="red",fg="black",font="TkFixedFont",textvariable=input).grid(row=0,column=0,columnspan=4)
Button(root,text="1",fg="black",font="TkFixedFont",command=lambda:input.set(input.get()+"1"),height=1,width=4,bg="pink").grid(row=1,column=0)
Button(root,text="2",fg="black",font="TkFixedFont",command=lambda:input.set(input.get()+"2"),height=1,width=4,bg="green").grid(row=1,column=1)
Button(root,text="3",fg="black",font="TkFixedFont",command=lambda:input.set(input.get()+"3"),height=1,width=4,bg="yellow").grid(row=1,column=2)
Button(root,text="/",fg="black",font="TkFixedFont",command=lambda:input.set(input.get()+"/"),height=1,width=4,bg="white").grid(row=1,column=3)
Button(root,text="4",fg="black",font="TkFixedFont",command=lambda:input.set(input.get()+"4"),height=1,width=4,bg="white").grid(row=2,column=0)
Button(root,text="5",fg="black",font="TkFixedFont",command=lambda:input.set(input.get()+"5"),height=1,width=4,bg="yellow").grid(row=2,column=1)
Button(root,text="6",fg="black",font="TkFixedFont",command=lambda:input.set(input.get()+"6"),height=1,width=4,bg="green").grid(row=2,column=2)
Button(root,text="*",fg="black",font="TkFixedFont",command=lambda:input.set(input.get()+"*"),height=1,width=4,bg="pink").grid(row=2,column=3)
Button(root,text="7",fg="black",font="TkFixedFont",command=lambda:input.set(input.get()+"7"),height=1,width=4,bg="green").grid(row=3,column=0)
Button(root,text="8",fg="black",font="TkFixedFont",command=lambda:input.set(input.get()+"8"),height=1,width=4,bg="pink").grid(row=3,column=1)
Button(root,text="9",fg="black",font="TkFixedFont",command=lambda:input.set(input.get()+"9"),height=1,width=4,bg="white").grid(row=3,column=2)
Button(root,text="+",fg="black",font="TkFixedFont",command=lambda:input.set(input.get()+"+"),height=1,width=4,bg="yellow").grid(row=3,column=3)
Button(root,text="c",fg="black",font="TkFixedFont",command=lambda:input.set(""),height=1,width=4,bg="yellow").grid(row=4,column=0)
Button(root,text="0",fg="black",font="TkFixedFont",command=lambda:input.set(input.get()+"0"),height=1,width=4,bg="white").grid(row=4,column=1)
Button(root,text="-",fg="black",font="TkFixedFont",command=lambda:input.set(input.get()+"-"),height=1,width=4,bg="pink").grid(row=4,column=2)
Button(root,text="=",fg="black",font="TkFixedFont",command=lambda:calculate(input.get()),height=1,width=4,bg="green").grid(row=4,column=3)
root.mainloop()
|
d15ee695e1a24a6d25be60c26137a8d2caafd827 | slott56/building-skills-oo-design-book | /code/test_wheel.py | 892 | 3.6875 | 4 | """
Building Skills in Object-Oriented Design V4
Wheel Examples
"""
from unittest.mock import MagicMock, Mock
import pytest
from wheel_examples import Wheel, Wheel_RNG
def test_wheel_rng():
mock_rng = Mock(
choice=Mock(return_value="bin1")
)
bins = ["bin1", "bin2"]
wheel = Wheel_RNG(bins, mock_rng)
value = wheel.choose()
assert value == "bin1"
mock_rng.choice.assert_called_with(bins)
def test_wheel_isolation():
mock_rng = Mock(
choice=Mock(return_value="bin1")
)
bins = ["bin1", "bin2"]
wheel = Wheel(bins)
wheel.rng = mock_rng # Replaces random.Random
value = wheel.choose()
assert value == "bin1"
mock_rng.choice.assert_called_with(bins)
def test_wheel_integration():
bins = ["bin1", "bin2"]
wheel = Wheel(bins)
wheel.rng.seed(42)
value = wheel.choose()
assert value == "bin1"
|
5e37e1e7d5c51fb873c637f2053884c508cbcdbe | slott56/building-skills-oo-design-book | /code/bin_examples.py | 1,592 | 3.6875 | 4 | """
Building Skills in Object-Oriented Design V4
"""
from typing import Iterable
from dataclasses import dataclass
@dataclass(frozen=True, order=True)
class Outcome:
name: str
odds: int
class Bin1:
"""
>>> o1 = Outcome("This", 2)
>>> o2 = Outcome("That", 1)
>>> b1 = Bin1([o1, o2])
>>> len(b1)
2
>>> b1
Bin1([Outcome(name='That', odds=1), Outcome(name='This', odds=2)])
>>> o3 = Outcome("Third", 3)
>>> b1.add(o3)
>>> b1
Bin1([Outcome(name='That', odds=1), Outcome(name='Third', odds=3), Outcome(name='This', odds=2)])
"""
def __init__(self, outcomes: Iterable[Outcome]) -> None:
self.outcomes = frozenset(outcomes)
def __len__(self) -> int:
return len(self.outcomes)
def __repr__(self) -> str:
"""Impose order to make doctest cases work consistently."""
args = ", ".join(map(repr, sorted(self.outcomes)))
return f"{self.__class__.__name__}([{args}])"
def add(self, arg: Outcome) -> None:
self.outcomes |= frozenset([arg])
class Bin2(frozenset):
"""
>>> o1 = Outcome("This", 2)
>>> o2 = Outcome("That", 1)
>>> b2 = Bin2([o1, o2])
>>> len(b2)
2
We need to impose an ordering on the data.
>>> list(sorted(b2))
[Outcome(name='That', odds=1), Outcome(name='This', odds=2)]
>>> o3 = Outcome("Third", 3)
>>> b2 |= Bin2([o3])
We'll force an ordering on the data. here, also.
>>> list(sorted(b2))
[Outcome(name='That', odds=1), Outcome(name='Third', odds=3), Outcome(name='This', odds=2)]
"""
pass
|
9ff550bd05430e29373fd8774c982eeaac26436f | trilliwon/LeetCode | /easy/binary-tree-paths.py | 822 | 3.890625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if not root:
return []
stack = []
stack.append((str(root.val), root))
paths = []
while stack:
path, node = stack.pop()
if node.left:
stack.append((path+'->'+str(node.left.val), node.left))
if node.right:
stack.append((path+'->'+str(node.right.val), node.right))
if node.left == None and node.right == None:
paths.append(path)
return paths
|
a47f3d24f79cca30c35d58f84aab2c930b7b0635 | trilliwon/LeetCode | /medium/add-two-numbers.py | 930 | 3.75 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
s = None
node = None
r = 0
while l1 != None or l2 != None:
left = 0 if l1 == None else l1.val
right = 0 if l2 == None else l2.val
r = left + right + r
newNode = ListNode(r % 10)
r = r // 10
if s == None:
s = newNode
node = s
else:
node.next = newNode
node = node.next
l1 = None if l1 == None else l1.next
l2 = None if l2 == None else l2.next
if r > 0:
node.next = ListNode(r)
return s
|
9c956501df5e5f6b8603da3f7b24e12bb0926c85 | trilliwon/LeetCode | /easy/base-7.py | 511 | 3.625 | 4 | class Solution:
def convertToBase7(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0:
return "0"
answer = []
isNegativeNumber = num < 0
num = (-1)*num if isNegativeNumber else num
while num > 0:
answer.append(str(num % 7))
num = num // 7
if isNegativeNumber:
answer.append('-')
answer.reverse()
return ''.join(answer)
|
b3d7ecb6aaa236ca1e5ddf98f19ba07b11843d40 | trilliwon/LeetCode | /easy/symmetric-tree.py | 1,237 | 3.90625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
leftStack = []
rightStack = []
self.addLeftToStack(leftStack, root)
self.addRightToStack(rightStack, root)
while leftStack and rightStack:
if len(leftStack) != len(rightStack):
return False
left = leftStack.pop()
right = rightStack.pop()
if left.val != right.val:
return False
else:
if left.right:
self.addLeftToStack(leftStack, left.right)
if right.left:
self.addRightToStack(rightStack, right.left)
return True
def addLeftToStack(self, leftStack, node):
while node != None:
leftStack.append(node)
node = node.left
def addRightToStack(self, rightStack, node):
while node != None:
rightStack.append(node)
node = node.right
|
4945122a94e19bbeaf097b06ef92d616eeb40e49 | trilliwon/LeetCode | /easy/path-sum-iii.py | 1,249 | 3.8125 | 4 | import queue
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def dfs(self, root, sum):
stack = []
stack.append((root, root.val))
numOfPath = 0
while stack:
node, s = stack.pop()
if s == sum:
numOfPath += 1
if node.right != None:
stack.append((node.right, node.right.val + s))
if node.left != None:
stack.append((node.left, node.left.val + s))
return numOfPath
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: int
"""
if root == None:
return 0
ans = 0
que = queue.Queue()
que.put(root)
while not que.empty():
node = que.get()
ans += self.dfs(node, sum)
if node.right != None:
que.put(node.right)
if node.left != None:
que.put(node.left)
return ans
|
81c75f3f24f09d74f5f8ddca7584b7e4481833db | trilliwon/LeetCode | /medium/path-sum-ii.py | 1,118 | 3.59375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
if not root:
return []
stack = []
stack.append(([root.val], root))
paths = []
while stack:
path, node = stack.pop()
if node.left:
t_path = copy.deepcopy(path)
t_path.append(node.left.val)
stack.append((t_path, node.left))
if node.right:
t_path = copy.deepcopy(path)
t_path.append(node.right.val)
stack.append((t_path, node.right))
if node.left == None and node.right == None:
s = 0
for x in path:
s += x
if s == sum:
paths.append(path)
return paths
|
cb19f8de71ae92cae46b69d57803a64847891a9d | trilliwon/LeetCode | /easy/balanced-binary-tree.py | 1,408 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def depth(self, root):
if not root:
return 0
stack = []
stack.append((root, 1))
depthlist = []
while stack:
curr, depth = stack.pop()
if curr.right != None:
stack.append((curr.right, depth + 1))
if curr.left != None:
stack.append((curr.left, depth + 1))
if curr.right == None and curr.left == None:
depthlist.append(depth)
return max(depthlist)
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root == None:
return True
if root.left != None and root.right == None:
return abs(self.depth(root.left) - 0) <= 1
elif root.right != None and root.left == None:
return abs(self.depth(root.right) - 0) <= 1
if root.left != None and root.right != None:
if abs(self.depth(root.left) - self.depth(root.right)) > 1:
return False
else:
return self.isBalanced(root.left) and self.isBalanced(root.right)
else:
return True
|
41d6bb00d8411fb8aa3dab8607c7ddd0919c6e3e | tushach/Python-projects | /encrypt.py | 359 | 3.828125 | 4 | alpha="abcdefghijklmnopqrstuvwxyz"
newmessage=''
msg=input("Enter your message: ")
key=int(input("Enter a key for your message: "))
for char in msg:
if char in alpha:
pos=alpha.find(char)
newpos=(pos+key)%26
newchar=alpha[newpos]
newmessage+=newchar
else:
newmessage+=char
print("The encrypted message is: %s"%newmessage)
|
eaa4cb4848a01460f115a9dec5fe56ef329fc578 | Blu-Phoenix/Final_Calculator | /runme.py | 2,632 | 4.40625 | 4 | """
Program: Final_Calculator(Master).py
Developer: Michael Royer
Language: Python-3.x.x
Primum Diem: 12/2017
Modified: 03/28/2018
Description: This program is a calculator that is designed to help students know what finals they should focus on and which ones they can just glance over.
Input: The user will be asked four questions about their class. They are as follows: the total points possible, the amount of points earned, their desired percentage score, and the amount of points the are left in the class.
Output: This program in output the minimum score they have to make on their final to get their desired score.
"""
# The Input function asks the user for four different questions, and returns their answers as a float.
def Input():
total_points = float(input("Enter the total points possible in your class.""\n"))
your_points = float(input("Enter the amount of points that you have earned in your class up until this point.""\n"))
desired_score = float(input("Enter the percentage score that you want to earn in the class (ex. 90, 80 or 84.5).""\n"))
points_LOTB= float(input("Enter the amount of points possible that are left in your class.""\n"))
return total_points, your_points, desired_score, points_LOTB
# The Calculation function the controls the processing part of the program.
def Calculation(total_points, your_points, desired_score, points_LOTB):
# This if-statement fixes the 'divide by zero' bug.
if points_LOTB <= 0:
print ("Sorry mate your class is over.")
Input()
points_need = total_points * (desired_score / 100)
D_score_needed = (points_need - your_points) / points_LOTB
score_needed = D_score_needed * 100
return score_needed, desired_score
# The Output function that controls the output part of the program.
def Output(score_needed, desired_score):
if score_needed <= 0:
print ("If you skip your final and still pass your class with a", desired_score, "percent.")
if score_needed > 100:
print ("You can't make a", desired_score, "percent in your class even if you make a perfect score on your test.")
if (score_needed <= 100 and score_needed >= 0):
print ("You need to make at least", score_needed, "percent on your test to make a", desired_score, "percent in your class.")
# The Main function excuites the program in order.
def Main():
[total_points, your_points, desired_score, points_LOTB] = Input()
[score_needed, desired_score] = Calculation(total_points, your_points, desired_score, points_LOTB)
Output(score_needed, desired_score)
# This block excuites the program
Main()
|
d0c49942872a33e70d8a35133578d09963c761d4 | Andrewlastrapes/car_calculator | /newcarcalc.py | 1,125 | 4.0625 | 4 |
def newcar():
input("How much is a new car going to cost you per month? Please hit enter to start")
p = int(input("Please enter total cost of car: "))
r = float(input("Please enter interest rate as a whole number(example: 15.6% = 15.6): National average is around 4.5%): "))
t = int(input("These payments would last for how many months?: "))
dp = int(input("Please enter the downpayment percentage as a whole number: example: 20% = 20: "))
afterdp = p - (p * dp/100)
downpay = p - afterdp
downpay = round(downpay, 2)
interest = afterdp * (r/100) * (t/12)
interest = round(interest, 2)
monthly_payment_bt = (afterdp + interest)/t
monthly_payment_bt = round(monthly_payment_bt, 2)
monthly_payment = (monthly_payment_bt * .07) + monthly_payment_bt
monthly_payment = round(monthly_payment, 2)
t = round(t/12, 2)
return("Your monthly payment would be $" + str(monthly_payment) + " for " + str(t) + " years, and a downpayment of $" + str(downpay))
print(newcar())
# Car payment should not exceed 10% of your total gross income per month.
# Try not to finance a car longer than 60 months
|
449219be2325b86c67ba461085f50b70fffbe537 | yujunjiex/20days-SuZhou | /day01/task05.py | 1,552 | 4.125 | 4 | # coding: UTF-8
"""
卡拉兹(Callatz)猜想:
对任何一个自然数n,如果它是偶数,那么把它砍掉一半;如果它是奇数,那么把(3n+1)砍掉一半。
这样一直反复砍下去,最后一定在某一步得到n=1。
卡拉兹在1950年的世界数学家大会上公布了这个猜想,传说当时耶鲁大学师生齐动员,拼命想证明这个貌似很傻很天真的命题,
结果闹得学生们无心学业,一心只证(3n+1),以至于有人说这是一个阴谋,卡拉兹是在蓄意延缓美国数学界教学与科研的进展……
我们今天的题目不是证明卡拉兹猜想,而是对给定的任一不超过1000的正整数n,简单地数一下,需要多少步(砍几下)才能得到n=1?
输入格式:每个测试输入包含1个测试用例,即给出自然数n的值。
输出格式:输出从n计算到1需要的步数。
输入样例:
3
输出样例:
5
"""
def callatz_num_steps(num: int):
"""
获取1000以内的自然数按照卡拉兹(Callatz)猜想所需的步骤
:param num: 自然数
:return: steps:从n计算到1所需的步骤
"""
steps = 0
while True:
if num % 2 == 0: # 偶数
num = num / 2
else: # 奇数
num = (3*num+1) / 2
steps += 1
print("经过第{}步,当前值为{}".format(steps, num))
if num == 1:
return steps
if __name__ == '__main__':
steps = callatz_num_steps(3)
print(steps)
|
1aa2f192350934e720cb2546d7a7eebf9e09732e | un1xer/python-exercises | /zippy.py | 1,073 | 4.59375 | 5 | # Create a function named combo() that takes two iterables and returns a list of tuples.
# Each tuple should hold the first item in each list, then the second set, then the third,
# and so on. Assume the iterables will be the same length.
# combo(['swallow', 'snake', 'parrot'], 'abc')
# Output:
# [('swallow', 'a'), ('snake', 'b'), ('parrot', 'c')]
# If you use list.append(), you'll want to pass it a tuple of new values.
# Using enumerate() here can save you a variable or two.
# dict.items() - A method that returns a list of tuples from a dictionary.
# Each tuple contains a key and its value.
def combo(list1, list2):
combined_list = []
print(combined_list)
for item1, item2 in enumerate(list2):
print(item1, item2)
temp_list = (list1[item1], item2)
combined_list.append(temp_list)
print(combined_list)
return (combined_list)
list1 = ['swallow', 'snake', 'parrot']
list2 = ['a', 'b', 'c']
combo(list1, list2)
# alternate solution using zip()
list3 = zip(list1, list2)
print (list(list3))
# print(combo(combined_list))
|
93fd79478aa591de5d11976f78f7e6e856589cca | un1xer/python-exercises | /teachers.py | 1,763 | 4.0625 | 4 | # Create a function named most_classes that takes
# a dictionary of teachers and returns the teacher with the most classes.
# The dictionary will be something like:
# {'Jason Seifer': ['Ruby Foundations', 'Ruby on Rails Forms', 'Technology Foundations'],
# 'Kenneth Love': ['Python Basics', 'Python Collections']}
#
# Often, it's a good idea to hold onto a max_count variable.
# Update it when you find a teacher with more classes than
# the current count. Better hold onto the teacher name somewhere
# too!
#
# Your code goes below here.
treehouse_dict = {'Jason Seifer': ['Ruby Foundations', 'Ruby on Rails Forms', 'Technology Foundations'],
'Kenneth Love': ['Python Basics', 'Python Collections','Write Better Python', 'Object-Oriented Python'], 'Phoebe Espiritu': ['Design & Code', 'Entrepreneurship', 'GitHub for Non-Programmers']}
def most_classes(my_dict):
max_count = 0
max_count_teacher = ''
for key in my_dict:
if len(my_dict[key]) >= max_count:
max_count = len(my_dict[key])
max_count_teacher = key
print(key, len(my_dict[key]))
return(max_count_teacher)
def num_teachers(my_dict):
return(len(list(my_dict.keys())))
def stats(my_dict):
teacher_list = []
for key in my_dict:
teacher_list.append([key, len(my_dict[key])])
# print (teacher_list)
return(teacher_list)
def courses(my_dict):
course_list = []
for value in my_dict.values():
course_list = course_list + value
# print(course_list)
return(course_list)
most_classes(treehouse_dict)
print(most_classes(treehouse_dict))
num_teachers(treehouse_dict)
print(num_teachers(treehouse_dict))
stats(treehouse_dict)
print(stats(treehouse_dict))
courses(treehouse_dict)
print(courses(treehouse_dict))
|
b6c98e63330665bbf33d9952924ea921bc5e7c01 | un1xer/python-exercises | /data/file-test.py | 781 | 3.859375 | 4 | # read file countries.txt
f = open("countries.txt", "r")
countries = []
for line in f:
# removes newline at the end of each line from text file
line = line.strip()
# prints each line in countries.txt
print(line)
# creates list of countries
countries.append(line)
print (countries)
# loops through and prints countries that start with "P"
counter = 0
for country in countries:
if country[0] == "P":
print(country)
counter += 1
print ("There are {} countries that start with P".format(counter))
# loops through and prints countries that contain 'ar'
counter = 0
for country in countries:
if "ar" in country:
print(country)
counter += 1
print ("There are {} countries that contain 'ar'".format(counter))
f.close()
|
4c38fd6ace4910b56cd787280fe4b3de9d073ee6 | tshihui/pypaya | /introToPython/q2_15.py | 490 | 3.984375 | 4 | # 2.15
num1 = float(input('Please input first number: '))
num2 = float(input('Please input second number: '))
num3 = float(input('Please input third number: '))
min = num1
min2 = num2
min3 = num3
if (min < min2) & (min2 > min3):
min2 = num3
min3 = num2
if (min > min2) & (min > min3):
min3 = min
if (min2 < min3):
min = min2
min2 = num3
else:
min = min3
if (min > min2) & (min < min3):
min = min2
min2 = num1
print(min, min2, min3)
|
b7f4f3872363f50ad2649090dd3437614be8230d | tshihui/pypaya | /programmingQuestions/fibonacci.py | 756 | 4.25 | 4 | ###############
## Fibonacci ##
## 2/2/2019 ##
###############
def fib(n):
""" Fibonacci sequence """
if n == 1 :
return([0])
print('The first ', n, ' numbers of the Fibonacci sequence is : [0]')
elif n == 2:
return([0,1])
print('The first ', n, ' numbers of the Fibonacci sequence is : [0, 1]')
elif n > 2:
seq = [0,1]
for k in range(n-2):
seq.append(sum(seq[k:k+2]))
print('The first ', n, ' numbers of the Fibonacci sequence is :', seq)
return(seq)
#######################
if __name__ == "__main__":
import sys
if len(sys.argv) < 2:
print("Please state n to compute fibonacci sequence.")
else:
n = int(sys.argv[1])
fib(n)
|
6f5407397ab06b59760a4b8dff90f99adbb29ca9 | tshihui/pypaya | /pythonTutorial/tutorial7.py | 5,276 | 4.375 | 4 | if __name__ == '__main__':
print('formatting outputs with f or F')
year = 1000
event = 10
print(f'the number of {event} in the last {year} years')
print('another way to format output')
yes = 248952
no = 183095
percent = no/yes
print('{:-9} yes votes {:2.2%}'.format(yes, percent))
s = 'hello world\n'
print('Difference between str and repr: repr will print the version read by interpreter')
print(str(s))
print(repr(s))
print('/n more on formatting')
print('using the format {var:digitsBeforeDec.digitsf}')
import math
print(f'the value of pi is approx {math.pi:.3f}')
tab = {'ohe' : 123, 'oeu':103, 'hwo':139}
for tag, code in tab.items():
print(f'{tag:10} ==> {code:10d}')
print('{word!r} will apply repr to word')
print('{word!s} will apply ascii to word')
said = 'awwww'
print(f'using !r: She said {said!r}')
print(f'without !r, 10 letters spaces: She said {said:10}.')
print('\nusing str.format()')
print('We are going to be the {} awesome {}'.format('most', 'people'))
print('insert numbers in the {} in strings determine positions of strings')
print('We are going to be the {1} awesome {0}'.format('most', 'people'))
print('This method works with keywords in {} too')
print('We are going to be the {word1} awesome {word2}'.format(word1 = 'most', word2 = 'people'))
print('Both positional and keyword arguments:')
print("{date}'s breakfast will be {1} and {0}".format('eggs', 'spam', date = 'tomorrow'))
menu = {'ham': 14, 'hotdogs': 5, 'tea': 2}
print('Ham: {0[ham]:d}; Hotdogs: {0[hotdogs]:d}; Tea: {0[tea]:d}'.format(menu))
print('Ham: {ham:d}; Hotdogs: {hotdogs:d}; Tea: {tea:d}'.format(**menu))
for x in range(1, 11):
print('{0:2d}, {1:3d}, {2:4d}'.format(x, x**2, x**3))
print('manual string formatting')
print('right padded')
for x in range(1, 11):
print(repr(x).rjust(2), repr(x**2).rjust(3), repr(x**3).rjust(4), end = '\n')
print('center')
for x in range(1, 11):
print(repr(x).center(2), repr(x ** 2).center(3), repr(x ** 3).center(4), end='\n')
print('zfill : pads 0')
for x in range(1, 11):
print(repr(x).zfill(2), repr(x ** 2).zfill(3), repr(x ** 3).zfill(4), end='\n')
print('old string formatting')
import math
print('the value of pi is %5.3f.' % math.pi)
print('--- Reading & Writing Files')
print('reading file with the format: open("filename", "option"')
print('read options are: r= read, w = writing(overwrite), a=append, r+= read & write, b= binary')
print('text mode will convert line endings depending on platform\n, \\n for linus and \\r\\n for windows\n when \
reading, converting \\n to platform readable when writing.')
print('It is better to read files using "with": \n with open("filename") as f:\n read_data = f.read()\n\
This ensures that file will be closed properly.')
print('else, close file with: f.close()')
import os
print('\nTry reading file:')
with open('func6.py') as f:
testDat = f.read()
print(repr(testDat))
print(len(testDat))
print('f.closed will print {}, suggesting file no longer available:'.format(f.closed))
print('\nIf we read without using "with": f = open("filename"):')
f = open('func6.py')
print('The first time f.read() is ran, we get:\n', f.read())
print('Running f.read() again, we get:', f.read().center(10))
print('The first time f.read() is ran, all the lines were already exhausted.')
f = open('func6.py')
print('\nTo read line by line, we use readline()')
print('First line:', f.readline())
print('readline() prints "" when EOL is reached.')
print('for loop can be used to read over the whole file with readline:')
line = 0
for fl in f:
line += 1
print(line, ':', f.readline())
print('Note that first line of the file is not read in for loop as it was already read in previous steps')
print('Alternatively, use readlines() or list(f)')
print('Using list:', list(open('func6.py')))
print('Using readlines:', open('func6.py').readlines())
print('Either method return lines in a list')
print('Compare these to f.read() which stores the whole file as a continuous string.')
print('to write a string to the existing file, f.write() can be used')
f = open('func6.py', 'a')
print('Remember to write, the file has to be open with "w" or "r+" but this will overwrite the whole file')
print('To append, we use "a"', f.write('#test'))
print('f.write() will return length of string written')
f.close()
dat = open('func6.py').readlines()
print('Now check the last line of the file', dat[len(dat)-1])
print('\nMoving into JSON')
print('Converting python data into string rep: serializing')
print('Reconstructing data from string rep: deserializing')
x = [1, 'oh', 'well']
import json
print('Using json dump to serialize object:', json.dumps(x))
print('We can directly dump serialized object into a file using json.dump(x, openedfile)')
print('To deserialize json file (string back to data), use object = json.load(jsonfile)')
print('\n\n--- End of Tutorial 7 ---') |
63e96a978bb28a007211fd0d3a0529af8ac79b7a | tshihui/pypaya | /codility_practices/binaryGap.py | 2,716 | 3.65625 | 4 | #########################################################
#------- Solution to identify largest binary gap -------#
#########################################################
#-----------------------------------------#
#---------- Final Version ----------------#
#-----------------------------------------#
#----- Functions -----#
def find0(binNum):
# find first 1
pos1 = binNum.find('1')
# find second 1
pos2 = binNum.find('1', pos1+2)
# return number of 0s
count0 = binNum[pos1:pos2+1].count('0')
# return cut string
newBinNum = binNum[pos2:len(binNum)]
return(count0, newBinNum)
def binaryGap(N):
# Needs to be improved
binNum = "{0:b}".format(N)
count0s = []
if binNum.count('0') > 0 and binNum.count('1') > 1:
while(len(binNum) > 2):
binAns = find0(binNum)
count0s.append(binAns[0])
binNum = binAns[1]
return(max(count0s))
else:
return(0)
#----- Main function -----#
if __name__ == '__main__':
print('---------- Running test cases: ')
print('When N = 53: ')
print(binaryGap(53))
print('')
print('When N = 1456: ')
print(binaryGap(1456))
print('')
print('When N = 10555501: ')
print(binaryGap(10555501))
print('')
#-------------------------------------#
#---------- Version 2 ----------------#
#-------------------------------------#
def find0(binNum):
# find first 1
pos1 = binNum.find('1')
# find second 1
pos2 = binNum.find('1', pos1+2)
# return number of 0s
count0 = binNum[pos1:pos2+1].count('0')
# return cut string
newBinNum = binNum[pos2:len(binNum)]
if count0 == 0:
return(0)
else:
return(count0, newBinNum)
def binaryGap(N):
# Needs to be improved
binNum = "{0:b}".format(N)
count0s = []
if binNum.count('0') > 0 and binNum.count('1') > 1:
while(len(binNum) > 2):
binAns = find0(binNum)
count0s.append(binAns[0])
binNum = binAns[1]
return(max(count0s))
else:
return(0)
#-------------------------------------#
#---------- Version 1 ----------------#
#-------------------------------------#
def binaryGap(N):
# Needs to be improved
binNum = "{0:b}".format(N)
count0s = []
pos1, pos2 = 0, 0
if binNum.count('0') > 0 and binNum.count('1') > 1:
pos1 = binNum.find('1')
while (pos1+2) <= len(binNum):
pos2 = binNum.find('1', pos1+2)
count0s.append(binNum[pos1:pos2+1].count('0'))
pos1 = pos2
return(max(count0s))
else:
return(0)
|
d5688cef9797d4ab6a2f8c48a36bb813e317600f | goufix-archive/py-exercises | /exercicios/sequencial/18.py | 1,643 | 4.125 | 4 | import math
name = 'alifer'
# Faça um Programa para uma loja de tintas. O programa deverá pedir
# o tamanho em metros quadrados da área a ser pintada.
# Considere que a cobertura da tinta é de 1 litro para cada
# 6 metros quadrados e que a tinta é vendida em latas de 18 litros,
# que custam R$ 80,00 ou em galões de 3,6 litros, que custam R$ 25,00.
# Informe ao usuário as quantidades de tinta a serem compradas e os respectivos preços em 3 situações:
# 1. comprar apenas latas de 18 litros;
# 2. comprar apenas galões de 3,6 litros;
# 3. misturar latas e galões, de forma que o preço seja o menor.
# Acrescente 10% de folga e sempre arredonde os valores para cima, isto é,
# considere latas cheias.
LITRO_TINTA_POR_METRO_QUADRADO = 6
LATA_TINTA = 18
LATA_PRECO = 80
GALAO_TINTA = 3.6
GALAO_PRECO = 25
area = float(input("Quantos metros² de deseja pintar?\n"))
litros_a_serem_usados = (area / LITRO_TINTA_POR_METRO_QUADRADO) * 1.1
print('litros a serem usados:', litros_a_serem_usados)
latas = math.floor(litros_a_serem_usados / LATA_TINTA)
galoes = math.ceil(
(litros_a_serem_usados - (LATA_TINTA * latas)) / GALAO_TINTA)
print("Latas a serem usadas:", latas)
print("Galoes a serem usados:", galoes)
print("usando:", galoes, "galões, você vai gastar", (galoes * GALAO_PRECO))
print("usando:", latas, "latas, você vai gastar", (latas * LATA_PRECO))
print(" Comprando apenas latas você vai gastar: R$",
(math.ceil(litros_a_serem_usados / LATA_TINTA) * LATA_PRECO))
print(" Comprando apenas galões você vai gastar: R$",
(math.ceil((area / LITRO_TINTA_POR_METRO_QUADRADO) / GALAO_TINTA) * GALAO_PRECO))
|
eb9560d4677463b71c5b709a4f1f6013c0c26314 | brunolcarli/AlgoritmosELogicaDeProgramacaoComPython | /livro/code/sistemaPython/main.py | 1,011 | 4.28125 | 4 | import funcionalidades #importa o modulo de funcionalidades que criamos
while True: #criamos um loop para o programa
print('#'*34) #fornecemos um menu de opcoes
print(">"*11,"BEM-VINDO","<"*11)
print("Escolha a operacao desejada")
print("[1] Cadastrar produto")
print("[2] Verificar produtos cadastrados")
print("[3] Buscar produto")
print("[4] Compra")
print("[5] Sair do sistema")
print("#"*34)
entrada = input() #recebe a entrada
if entrada == '1': #fornece a funcionalidade de acordo com a opcao
funcionalidades.cadastro()
elif entrada == '2':
funcionalidades.verProdutos()
elif entrada == '3':
funcionalidades.buscaProdutos()
elif entrada == '4':
funcionalidades.compra()
elif entrada == '5':
break
else: #e uma mensagem avisando quando a entrada for invalida
print("#"*34)
print("Operacao invalida")
print("#"*34)
|
2fba35593cff0e6f6397669b60e63d90ca9bc504 | brunolcarli/AlgoritmosELogicaDeProgramacaoComPython | /livro/code/capitulo5/exercicio9.py | 779 | 3.890625 | 4 | lista = list(range(10)) #criar uma lista com 10 posicoes
for pos in lista: #para cada posicao na lista
lista[pos] = int(input("Insira um numero: ")) #entre com um inteiro e atribua a posicao
for i in range(10): # vamos contar de um a 10, i sera o contador
j = i+1 # j sera o contador para o numero vizinho
for j in range(10):
if lista[i] < lista[j]: #se o indice de posicao i for menor que o indice de posicao j
troca = lista[i] #fazemos uma troca, guardamos o numnero na posicao i
lista[i] = lista[j] #colocamos o numero de posicao j no lugar da posicao i
lista[j] = troca #colocamos o numero da posicao i no lugar da posicao j
for numero in lista: #escreva os itens da lista ordenada
print(numero)
|
da6fddd71439494fa40fa128eb958f8aee758809 | brunolcarli/AlgoritmosELogicaDeProgramacaoComPython | /livro/code/capitulo3/exemplo19.py | 755 | 3.9375 | 4 |
#solicitamos o nome da disciplina
disciplina = input("Insira o nome da disciplina: ")
#solicitamos as notas de cada bimestre
nota1 = float(input("Insira a nota do 1 Bimestre: "))
nota2 = float(input("Insira a nota do 2 Bimestre: "))
nota3 = float(input("Insira a nota do 3 Bimestre: "))
nota4 = float(input("Insira a nota do 4 Bimestre: "))
#calculamos a media
media = (nota1 + nota2 + nota3 + nota4) / 4
#exibimos a media e a disciplina
print("Disciplina: ", disciplina)
print("Media: ", media)
if media >= 7.0: #se a media for menor que 7.0 o aluno e reprovado
print("Aprovado")
elif media >= 6.0 and media <= 6.9: # se a media for entre 6.0 e 6.9 recuperacao
print("Recuperacao")
else: # senao e aprovado
print("Reprovado")
|
fc80005a87f4659595c0e83bef75e7c1e2c22cef | brunolcarli/AlgoritmosELogicaDeProgramacaoComPython | /livro/code/capitulo6/exemplo53.py | 451 | 4.1875 | 4 | def quadrado(numero): #a definicao de uma funcao e igual a de um procedimento
return numero**2 #usamos a instrucao return para retornar um valor
entrada = int(input("Insira um numero: ")) #pedimos um numero
quad = quadrado(entrada) #chamamos a funcao e guardamos o retorno em quad
print("O quadrado de %i e %i" % (entrada, quad)) #escrevemos o resultado
print("O quadrado do quadrado e ", quadrado(quad)) #o retorno tambem pode ser impresso
|
e8677cd29a9cebe156ac92b710e3b845afe30e16 | brunolcarli/AlgoritmosELogicaDeProgramacaoComPython | /livro/code/capitulo5/exemplo31.py | 338 | 3.984375 | 4 | lista = ["banana", "queijo", "trigo", "Azeite"] #lista inicial
print(len(lista)) #verifique o tamanho da lista
print(lista) #verifique os itens na lista
lista.append("cenoura") #adicione a cenoura no fim da lista
print(len(lista)) #verifique novamente o tamanho da lista
print(lista) #verifique novamente os itens na lista
|
57ab37112b0079458b6764b8a553ae350ec67d85 | brunolcarli/AlgoritmosELogicaDeProgramacaoComPython | /livro/code/capitulo6/exemplo52.py | 983 | 4.0625 | 4 | def soma(a, b): #definimos um procedimento para soma com dois parametros
print("O resultado e: ", a + b) #o procedimento informa a soma dos dois parametros
def subt(a, b): #tambem definimos um procedimento para subtracao
print("O resultado e: ", a - b) #que informa a subtracao entre os parametros
num1 = int(input("Insira o primeiro numero ")) #leia o primeiro numero
num2 = int(input("Insira o segundo numero ")) #leia o segundo numero
print("Qual operacao deseja realizar?") #informe as opcoes de operacoes
print("[1] Soma \n[2]Subtracao")
escolha = int(input()) #leia a opcao desejada
if escolha == 1: #se escolher soma
soma(num1, num2) #chame o procedimento de soma e passe os numeros como argumento
elif escolha == 2: #se escolher subtracao
subt(num1, num2) #chame o procedimento de subtracao e passe os numeros como argumento
else: #senao
print("Escolha invalida") #informe uma mensagem de erro
|
da0d72971cfaa23536508e734299af13948a5411 | brunolcarli/AlgoritmosELogicaDeProgramacaoComPython | /livro/code/capitulo6/exemplo54.py | 381 | 3.59375 | 4 | def formatar(nome, sobrenome): #definimos a funcao
formatado = nome + " " + sobrenome #processamento da funcao
return formatado.title() #retorno da funcao
meu_nome = "bruno" #string com nome
meu_sobrenome = "LUVIZotto CARLi" #string com sobrenome
nome_completo = formatar(meu_nome, meu_sobrenome) #chamada da funcao
print("Meu nome e ", nome_completo) #saida
|
d4c50b61906ef9e3e776d857ee857da89cd107a8 | maxts0gt/pythoneveryday | /D18_Turtle_Projects/circle.py | 566 | 3.828125 | 4 | from turtle import Turtle, Screen, color, colormode
import random
turtle = Turtle()
screen = Screen()
turtle.shape('turtle')
turtle.color('black')
colormode(255)
def random_color():
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
color = (r, g, b)
return color
def draw_spirograph(size_of_gap):
for _ in range(int(360 / size_of_gap)):
turtle.color(random_color())
turtle.circle(100)
turtle.setheading(turtle.heading() + size_of_gap)
draw_spirograph(5)
|
c1af06d29e4b657caa6cc3b4dd156a4e712f4fea | maxts0gt/pythoneveryday | /D46_Spotify_Project/main.py | 2,206 | 3.6875 | 4 | import requests
from bs4 import BeautifulSoup
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import pprint
pp = pprint.PrettyPrinter(indent=4)
CLIENT_ID = "YOUR CLIENT ID"
CLIENT_SECRET = "YOUR SECRET"
# 1. TODO Choose which year to select
which_date = input("Which year do you want to travel to? Type the date in this format YYYY-MM-DD: ")
# 2. TODO Crawling through top 100 songs on chosen date
response = requests.get(f"https://www.billboard.com/charts/hot-100/{which_date}")
url = response.text
soup = BeautifulSoup(url, "html.parser")
songs = soup.select("span.chart-element__information__song")
artists = soup.select("span.chart-element__information__artist")
song_list = [song.getText() for song in songs]
artist_list = [artist.getText() for artist in artists]
# 3. TODO Authenticating with Spotify
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri="http://example.com",
scope="playlist-modify-private",
cache_path=".cache"))
current_user = sp.current_user()
spotify_id = current_user["id"]
# playlist_id = spotify_id
# 4. TODO Finding URIs for top 100 days from billboard list
tracks_uri = []
for i in range(len(songs)):
try:
track = (sp.search(f"track: {song_list[i]}, artist: {artist_list[i]}", type="track"))
tracks_uri.append(track["tracks"]["items"][0]["uri"])
except IndexError:
print(f"There is no song called {song_list[i]} for Xmas on Spotify!")
# 5. TODO Creating a playlist
playlist_id = sp.user_playlist_create(user=spotify_id, name=f"{which_date} -> Billboard Best Songs!", public=False,
description="This is Xmas for U")
new_playlist_id = (playlist_id["uri"])
sp.playlist_add_items(playlist_id=new_playlist_id, items=tracks_uri, position=None)
# 6. TODO Checking items and playlist id
playlist_items = sp.playlist_items(playlist_id=new_playlist_id)
print(new_playlist_id)
print(playlist_items)
|
fed2a3c3fdf8ca62be24e4e351d6400c5acd1d61 | pns845/Dictionary_Practice | /exer_aug24.py | 231 | 3.703125 | 4 | db={'name':'Router1','IP':'1.1.1.1','username':'zframez','password':'zframez'}
print(db)
s=input("get data from user")
#print(db[s])
if s in db:
print("key is"+str(s))
print(db[s])
else:
db[s]='new value'
print(db)
|
96185701b42d39418c049884c2740c2fb3e2e938 | afakharany93/Numbers-game | /python3/cli_numbers_game.py | 1,411 | 3.546875 | 4 | from game_engine import NumGame
from help_string import help_string
help_string2 = help_string + """Method of input:\n
If you are guessing 12345 you will type 12345 and then you will press enter.\n
If you enter the character: e, the number will be revealed and you lose.\n
Press Enter to start\n
*******************************************************************************
"""
print(help_string2)
input()
play_again = True
while play_again:
print("*******************************************************************************")
play_again = False
game = NumGame()
solved = False
tries = 0
while not solved:
x = None
x = input('enter number: ')
flag, x, mesg_string = game.get_input(x)
if x == 'e':
print('the solution was {}'.format(game.num))
print('quit game')
break
if flag:
tries += 1
count, place = game.compare(x)
print( '{}) reply for {} is {}/{}'.format(tries,x, count, place))
if count == place == 5:
print('you won !')
print('your score is {}/100'.format(100-tries+1))
solved = True
y = input('play again? \n if yes type: y \n if no press any key excpet: y \n')
if y.lower() == 'y':
play_again = True
else:
print(mesg_string)
|
7553f4a04d4b684301ca8de86f83bd4c2f3bf3f0 | nishizumi-lab/sample | /python/basic/for/ex_obj.py | 184 | 4.03125 | 4 |
list = [1, 2, 3]
# list内の全要素が代入されるまで繰り返し
for x in list: # listの内容を1つずつ取り出してxに代入
print(x)# xを表示
print("End")
|
035992df7f2856f7fdbaa2ef068ab428086f3636 | nishizumi-lab/sample | /python/pandas/pivot_table.py | 524 | 3.53125 | 4 | # -*- coding: utf-8 -*-
import pandas as pd
def main():
# データフレームの初期化
df = pd.DataFrame({
'名前' : ['西住みほ', '秋山優花里', '武部沙織', '五十鈴華', '冷泉麻子'],
'身長' : [158, 157, 157, 163, 145]},
index = ['車長', '装填手', '通信手', '砲手', '操縦手']
)
# データ取り出し
df2 = pd.pivot_table(df, values='砲手', index=['車長', '装填手'], columns=['通信手'])
print(df2)
if __name__ == "__main__":
main()
|
77933b5cd45ab221fbd864bbeb69c8ab917dc5e9 | nishizumi-lab/sample | /python/sqlite/01_tutorial/05_select.py | 594 | 3.75 | 4 | # -*- coding: utf-8
import sqlite3
# データベース開く
db = sqlite3.connect("C:/github/sample/python/sqlite/00_sample_data/sarvant.db")
c = db.cursor()
# テーブル作成
c.execute('create table artoria (name text, atk int, hp int)')
# データ追加(レコード登録)
sql = 'insert into artoria (name, atk, hp) values (?,?,?)'
data = ('artoria',11221,15150)
c.execute(sql, data)
# コミット
db.commit()
# データ(レコード)取得
sql = 'select * from artoria'
for row in c.execute(sql):
print(row)
# クローズ
db.close()
"""
('artoria', 11221, 15150)
""" |
a7323112d0ff3509ec5191486446755ae0c9be21 | nishizumi-lab/sample | /python/basic/file/csv/update.py | 712 | 3.5625 | 4 | # -*- coding: utf-8 -*-
import csv
def read_csv(filename):
f = open(filename, "r")
csv_data = csv.reader(f)
list = [ e for e in csv_data]
f.close()
return list
def update_list2d(list, data):
for i in range(len(list)):
if list[i][0]==data[0]: list[i] = data
return list
def write_csv(filename, list):
with open(filename, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(list)
f.close()
def main():
filename = 'data.csv'
csv_data = read_csv(filename)
data = ["2017-01-01 01:00", 20, 50, 1030, 5]
csv_data2 = update_list2d(csv_data, data)
write_csv(filename, csv_data2)
if __name__=='__main__':
main()
|
2cb857d45ed8b9ef6f70e22707fb78611ca4c586 | nishizumi-lab/sample | /python/scikit/nn/sample01.py | 1,203 | 3.703125 | 4 | # -*- coding: utf-8
import numpy as np
# 活性化関数(ステップ関数)
def f(x):
x = np.array(x)
x[x>=0] = 1
x[x<0] = -1
return x
# 出力
def feed_forward(w, x):
return f(np.dot(w, x))
# 学習
def train(w, x, t, eps):
y = feed_forward(x, w)
# 出力と正解が異なれば重み更新
if(t != y):
w += eps * t * x
return w
def main():
# パラメータ
eps = 0.1 # 学習率
max_epoch = 100 # エポック最大数(計算回数の最大値)
# 教師データ
X = np.array([[1,0,0], [1,0,1], [1,1,0], [1,1,1]], dtype=np.float32) # 入力
t = np.array([-1,-1,-1,1], dtype=np.float32) # 正解ラベル
# 重みの初期化(適当な値をセット)
w = np.array([0,0,0], dtype=np.float32)
# 単純パーセプトロンで学習
for e in range(max_epoch):
# 学習
for i in range(t.size):
w = train(w, X[i], t[i], eps)
# 検証
y = f(np.sum(w*X, 1))
print("出力:", y)
print("正解:", t)
print("重み:", w)
if __name__ == "__main__":
main()
"""
出力: [-1. -1. -1. 1.]
正解: [-1. -1. -1. 1.]
重み: [-0.2 0.2 0.1 ]
""" |
7c8b0ac9e89b14cb5043edf4e109907bf708ddb1 | nishizumi-lab/sample | /python/csv/03_make_date_list/main.py | 1,078 | 3.578125 | 4 | # -*- coding: utf-8 -*-
import csv
import datetime as dt
# 365日*24時間分の日付を取得
def get_dates():
date = dt.datetime(2017, 1, 1, 0, 0)
dates = []
for i in range(365*24):
dates.append(date.strftime('%Y-%m-%d %H:%M'))
date += dt.timedelta(hours=1)
return dates
# 2次元リストをCSVファイルに保存
def write_csv(csv_path, data):
with open(csv_path, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(data)
def main():
# CSVファイルのパス
csv_path = "C:/github/sample/python/csv/03_make_date_list/data.csv"
# 365日*24時間分の日付を取得してリストを作成
dates = get_dates()
data = [dates] # 2次元リストに変換
data = list(map(list, zip(*data))) # リストの転置
# CSVにリストを書き込み
write_csv(csv_path, data)
if __name__=='__main__':
main()
"""
data.csvの中身
2017/1/1 0:00
2017/1/1 1:00
2017/1/1 2:00
2017/1/1 3:00
2017/1/1 4:00
︙
2017/12/31 21:00
2017/12/31 22:00
2017/12/31 23:00
"""
|
cd5d71c17faa96e5ab16a62ec44d01c084f0a39d | nishizumi-lab/sample | /python/basic/for/in/list.py | 237 | 3.59375 | 4 | # -*- coding: utf-8 -*-
def main():
# リストの初期化
names = ["宮内ひかげ", "富士宮このみ", "加賀山楓 "]
# 結果表示
for name in names:
print(name)
if __name__ == '__main__':
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.